Programming Algorithm-continuous positive integer sequence code for s (C)
Continuous positive integer sequence code for s (C)
Question: enter a positive number s to print all continuous positive number sequences (containing at least two numbers) for s ).
Starts from 1, 2, and adds. If the values are equal, the return value is returned. If the value is smaller than the value, the frontend value is shifted to the right. If the value is greater than the value, the backend value is shifted to the right until the backend moves to half of s.
Because there are two numbers, the decimal point is half, and the large number is half plus one, it is bound to end.
Code:
/* * 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;}
Output:
1 2 3 4 5 4 5 6 7 8