和为s的连续正整数序列 代码(C)
本文地址: http://blog.csdn.net/caroline_wendy
题目: 输入一个正数s, 打印出全部和为s的连续正数序列(至少含有两个数).
起始于1, 2, 相加, 假设相等则返回, 假设小于, 则前端递增右移, 假设大于, 则后端递增右移, 一直到后端移动到s的一半位置.
由于两个数, 小数为一半, 大数为一半加一, 则必定结束.
代码:
/* * main.cpp * * Created on: 2014.6.12 * Author: Spike */ /*eclipse cdt, gcc 4.8.1*/ #include <stdio.h> #include <stdlib.h> #include <string.h> 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