Sum of Consecutive Prime Numbers

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

题目大意呢,就是一个数如果有连续素数之和等于这个数,就加一次,最后输出这个数的次数.其实就是筛法就素数,再素数上在运算.
#include
<stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> int main() { int i,j,n,cmp,w,prime[10005]= {0}; prime[0]=prime[1]=1; for(i=2; i*i<=10000; i++) if(prime[i]==0) for(j=i*i; j<=10000; j+=i) prime[j]=1; //筛法求素数打表 while(scanf("%d",&n)!=EOF&&n) { cmp=w=0; for(i=2; i<=10000; i++) if(prime[i]==0) { cmp+=i; if(cmp==n) { w++; continue; }//别把这个数的本身忘掉....等于这个数了,在加素数肯定超出,故继续循环。 for(j=i+1; j<=10000; j++) { if(prime[j]==0) cmp+=j; if(cmp==n) { w++; break; } if(cmp>n) { cmp=0; break; } } } printf("%d\n",w); } return 0; }
posted @ 2013-07-16 20:31  会笑的虫  阅读(270)  评论(0)    收藏  举报