剑指Offer40 和为s的连续正数序列

 1 /*************************************************************************
 2     > File Name: 40_ContinuesSequenceWithSum.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年09月04日 星期日 15时52分42秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 
10 void PrintSmallToBig(int left, int right)
11 {
12     for (int i = left; i <= right; ++i)
13         printf("%d ", i);
14     printf("\n");
15 }
16 
17 // 输出所有和为sum的连续正数序列,至少两个数
18 void FindContinuesSequence(int sum)
19 {
20     if (sum < 3)
21         return;
22     
23     int left = 1;
24     int right = 2;
25     int middle = (1 + sum) / 2;
26     int current = left + right;
27     
28     while (left < middle)
29     {
30         if (current == sum)
31             PrintSmallToBig(left, right);
32         
33         while (current>sum && left<right)
34         {
35             current -= left;
36             left ++;
37             
38             if (current == sum)
39                 PrintSmallToBig(left, right);
40         }
41         right ++;
42         current += right;
43     }
44 }
45 
46 int main()
47 {
48     int sum = 9;
49     FindContinuesSequence(sum);
50     
51     return 0;
52 }

 

posted @ 2016-09-04 17:12  Juntaran  阅读(170)  评论(0编辑  收藏  举报