思路:
1,利用左右指针的思想
2,因为至少要有两个数,所以最大值为:(1+sum) / 2;
3,指定起始序列为1,2
举个例子,sum=9的情况
实现
void findContinuousSequence(int sum){ if(sum < 3){ return; } int small = 1; int big = 2; int mid = (1 + sum) >> 1; while (small < mid && big <= mid){ int curSum = 0; for (int i = small; i <= big; ++i) { curSum += i; } if(curSum == sum){ for (int i = small; i <= big; ++i) { if(i == big){ cout<<i<<"="; } else{ cout<<i<<"+"; } } cout<<sum<<endl; big++; } else if(curSum < sum){// 序列小于指定值,big++ big++; } else{ small++; } } }