用两个数small和big分别表示序列的最小值和最大值。首先把small初始化为1,big初始化为2,如果从small到big的序列的和大于n的话,向右移动small,相当于从序列中去掉较小的数字。如果从small到big的序列和小于n的话,向右移动big,相当于向序列中添加big的下一个数字,一直到small等于(1+n)/2,因为序列至少要有两个数字。
#include <iostream>
using namespace std;
void PrintContinuousSequence(int small, int big)
{
for(int i=small; i<=big; i++)
cout<<i<<" ";
cout<<endl;
}
void FindContinuousSequence(int n)
{
if(n<3)
return;
int small=1;
int big=2;
int middle=(n+1)/2;
int sum=small+big;
while(small < middle)
{
if(sum==n)
PrintContinuousSequence(small, big);
while(sum>n)
{
sum-=small;
small++;
if(sum==n)
PrintContinuousSequence(small, big);
}
big++;
sum+=big;
}
}
void main()
{
int n;
cout<<"请输入n:";
cin>>n;
FindContinuousSequence(n);
}