題目: 輸入一個正數s, 打印出所有和為s的連續正數序列(至少含有兩個數).
起始於1, 2, 相加, 如果相等則返回, 如果小於, 則前端遞增右移, 如果大於, 則後端遞增右移, 一直到後端移動到s的一半位置.
因為兩個數, 小數為一半, 大數為一半加一, 則必然結束.
代碼:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include#include #include void PrintContinuousSequence(int small, int big) { for (int i=small; i<=big; ++i) printf(%d , i); printf( ); } void FindContinuousSequence(int sum) { if (sum<3) return; int small = 1; int big = 2; int middle = (1+sum)/2; int curSum = small+big; while (small < middle) { if (curSum == sum) PrintContinuousSequence(small, big); while (curSum > sum && small < middle) { curSum -= small; small++; if(curSum == sum) PrintContinuousSequence(small, big); } big++; curSum += big; } } int main(void) { FindContinuousSequence(15); return 0; }
1 2 3 4 5 4 5 6 7 8