算法描述:
输入一个正数s,打印出所有和为s的连续正数序列
算法实现:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20/************************************************************************* > File Name: main.c > Author: cyf > Mail: 1097189275@qq.com > Created Time: 2016年03月26日 星期六 13时04分31秒 ************************************************************************/ #include "FindContinuousSequence.h" /* * 输入一个正数s,打印出所有和为s的连续正数序列(至少包含两个数) * 例如:15->[1-5],[4-6],[7-8] * */ int main() { int sum = 15; FindContinuousSequence(sum); return 0; }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15/************************************************************************* > File Name: FindContinuousSequence.h > Author: cyf > Mail: 1097189275@qq.com > Created Time: 2016年03月26日 星期六 13时07分35秒 ************************************************************************/ #ifndef FINDCONTINUOUSSEQUENCE_H #define FINDCONTINUOUSSEQUENCE_H #include <stdio.h> #include <stdlib.h> void FindContinuousSequence(int sum); void PrintContious(int start, int end); #endif
复制代码
1
2
3
4
5
6
7
8
9
10
11CC = gcc CFLAGS = -g %.o:%.c $(CC) -o $@ -c $(CFLAGS) $< main:main.o FindContinuousSequence.o $(CC) main.o FindContinuousSequence.o -o main $(CFLAGS) clean: rm -rf *.o main
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42/************************************************************************* > File Name: FindContinuousSequence.c > Author: cyf > Mail: 1097189275@qq.com > Created Time: 2016年03月26日 星期六 13时07分14秒 ************************************************************************/ #include "FindContinuousSequence.h" void FindContinuousSequence(int sum) { if(sum < 3) return; int small = 1; int big = 2; int middle = (1+sum)>>1; int curSum = small+big; while(small < middle) { if(curSum==sum) PrintContious(small, big); while(curSum >sum && small<middle) { curSum -= small; small++; if(curSum==sum) PrintContious(small, big); } big++; curSum += big; } } void PrintContious(int start, int end) { int i; for(i=start; i<=end; i++) printf("%d ", i); printf("n"); }
最后
以上就是温暖洋葱最近收集整理的关于输入一个正数s,打印出所有和为s的连续正数序列的全部内容,更多相关输入一个正数s,打印出所有和为s内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复