Sum of Consecutive Prime Numbers
2014-05-01 22:50
183 查看
Sum of Consecutive Prime Numbers
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 15 Accepted Submission(s) : 11
Problem Description
Some positive integers can be represented by a sum of one or more consecutive prime numbers. How many such representations does a given positive integer have? For example, the integer 53 has two representations 5 + 7 + 11 + 13 + 17 and 53. The integer 41 has
three representations 2+3+5+7+11+13, 11+13+17, and 41. The integer 3 has only one representation, which is 3. The integer 20 has no such representations. Note that summands must be consecutive prime
numbers, so neither 7 + 13 nor 3 + 5 + 5 + 7 is a valid representation for the integer 20.
Your mission is to write a program that reports the number of representations for the given positive integer.
Input
The input is a sequence of positive integers each in a separate line. The integers are between 2 and 10 000, inclusive. The end of the input is indicated by a zero.
Output
The output should be composed of lines each corresponding to an input line except the last zero. An output line includes the number of representations for the input integer as the sum of one or more consecutive prime numbers. No other characters should be inserted
in the output.
Sample Input
2
3
17
41
20
666
12
53
0
Sample Output
1
1
2
3
0
0
1
2
代码如下:
#include <iostream> #include <cstdio> using namespace std; const int N = 10005; int prime ; bool is_prime ; void do_prime() { int nprime = 0; for(int i = 1; i < N; i ++) { is_prime[i] = true; } is_prime[1] = false; for(int i = 2; i < N; i ++) { if(is_prime[i]) { prime[nprime++] = i; for(int j = i*i; j < N; j += i) { is_prime[j] = false; } } } } int main() { int n ; do_prime(); while(scanf("%d",&n),n) { int res = 0; int ans = 0; for(int i = 0; prime[i] <= n; i ++) { res = 0; for(int j = i; prime[j] <= n; j ++) { res += prime[j]; if(res == n){ ans ++; break; } else if(res > n) break; } } printf("%d\n",ans); } return 0; }
相关文章推荐
- 1.m分解阶乘之和
- 2.几种递推数
- 3.欧拉函数
- 4.快速幂模m算法
- 5.扩展欧几里得&&中国剩余定理
- 6.数论_web
- 组合数求模总结
- 【数论学习】奇素数分解为两个数平方和
- 【数论学习】数论分析证明
- 整数对
- Leftmost Digit
- POJ 3292.Semi-prime H-numbers
- NYOJ-954-N!
- HDU 1133 (数论 or DP、高精度;Java版)
- POJ 1061 青蛙的约会
- zoj_3621 Factorial Problem in Base K
- zoj_1657 Goldbach's Conjecture
- zoj_1526 Big Number
- poj_3210 Coins
- poj_1528 Perfection