编程题:输入一个正整数,若该数能用几个连续正整数之和表示,则输出所有可能的正整数序列

编程题:输入一个正整数,若该数能用几个连续正整数之和表示,则输出所有可能的正整数序列。


思路:对于n个连续正整数,若开始的数为m,则其和sum = n*m + n * (n-1) / 2;因此可以用两个for循环遍历实现

/************************************************************************/
/* 题目要求:输入一个正整数,若该数能用几个连续正整数之和表示,         */
/*           则输出所有可能的正整数序列                                 */                                    
/************************************************************************/

#include <iostream>
#include <string>
using namespace std;

void SucessNumbSum(unsigned int sum)
{
	unsigned int startNumb;   //连续正整数之和中的起始数
	unsigned int count;        //连续正整数的个数
	bool flag = false;
	for(startNumb = 1; startNumb < (sum + 1) / 2; ++startNumb)
	{
		for(count = 1; count < (sum + 1) / 2; ++count)
		{
			if(((startNumb * count) + (count * (count -1)) / 2) == sum)
			{
				if(false == flag)
					cout<< "the succession positive integer are: "<<endl;
				for(unsigned int i = 0;i < count; i++)
					cout<< startNumb + i <<"  ";
				cout<<endl<<endl;
				flag = true;
			}
			
		}
	}
	if(false == flag)
	{
		cout<<"No Succession positive integer beenn found" <<endl;
	}
}

int main()
{
	unsigned int number;
	cout<<"please enter a positive integer"<<endl;
	cin>>number;
	SucessNumbSum(number);
	return 0;
}



猜你喜欢

转载自blog.csdn.net/dby3579/article/details/52084578
今日推荐