POJ 2739(连续素数和) 解题报告

/*____________________________________________POJ 2739题________________________________________________ Sum of Consecutive Prime Numbers Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 10458 Accepted: 5914 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<stdio.h> int main() { int i,j,m,sum,count=0,result; int prime[5000]; //素数不会超过10000/2=5000个 prime[count++]=2; //先把2放进去 for(i=3;i<=10000;i+=2) //找出3到10000之间的素数,以2递增 { for(j=2; j<=i && (i%j!=0);j++); //判断i是否素数 if(j==i) //是素数 prime[count++]=i; } //FILE *fin=fopen("input.txt","r"); //fscanf(fin,"%d",&m); scanf("%d",&m); while(m) { result=0; //结果计数 for(int start=0; start<count; start++) { sum=0; //sum一定要在这里赋初值 for(i=start; i<count; i++) { if( (prime[i]+sum) < m ) sum+=prime[i]; else if( (prime[i]+sum) == m ) result++; else break; } } printf("%d/n",result); //fscanf(fin,"%d",&m); scanf("%d",&m); } return 0; } //第一版超时原因:每次输入的m我都从新计算从2到m的素数,其实只要计算一次从2到10000的素数, //然后存起来等着以后查就行了

你可能感兴趣的:(Integer,input,each,output,Numbers)