51.和爲n連續正數序列(數組)。

51.和爲n連續正數序列(數組)。
題目:輸入一個正數n,輸出所有和爲n連續正數序列。

例如輸入15,由於1+2+3+4+5=4+5+6=7+8=15,所以輸出3個連續序列1-5、4-6和7-8。




//coder:LEE 20120330
#include<iostream>
#include<cassert>
using namespace std ;
void Print(int start,int end){
	for (int i=start;i<=end;i++){
		cout<<i<<" ";
	}
	cout<<endl;
}
void OutPutSumOfSequenceEquelN(int n){
	assert(n>0);
	int start=1;
	int end=1;
	int sum=1;
	while(1){
		if (sum<n){
			end++;
			sum+=end;
		}
		else if(sum>n){
			sum-=start;
			start++;
		}
		else
		{
			Print(start,end);
			end++;//don't forget
			sum+=end;
		}
		if(end>=n)
			break;
	}
}
int main()
{
	OutPutSumOfSequenceEquelN(1);
	return 1;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章