標籤:mystra 編程演算法 和為s的連續正整數序列 代碼 c
和為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("\n");}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