http://poj.org/problem?id=2739
Sum of Consecutive Prime Numbers
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 23325 | Accepted: 12749 |
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.
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
Source
题意:
给定一个数字,询问有多少个连续素数序列之和等于该值。
例如:
53 有两种:53=5 + 7 + 11 + 13 + 17;53=53;
但是20=7 + 13 和20=3 + 5 + 5 + 7因为素数序列不连续,所以不满足。
思路:
素数打表后利用尺取法求解。
AC Code:
#include<stdio.h>
#include<string.h>
const int MYDD=1e4+1103;
int primenum[MYDD];
bool isprime[MYDD];
int GetPrime() {//筛选法判断素数
int num=0;
memset(isprime,true,sizeof(isprime));
isprime[0]=isprime[1]=false;
for(int j=2; j<=MYDD; j++) {
if(isprime[j]) {
primenum[num]=j;
for(int i=j*2; i<=MYDD; i=i+j)
isprime[i]=false;
num++;
}
}
return num;//返回 10000 之内的素数个数
}
int main() {
int dd=GetPrime();
while(1) {
int n;
scanf("%d",&n);
if(n==0) break;
// printf("%d*****\n",dd);
int ans=0;
int sum,l,r;
l=r=sum=0;
/*尺取法*/
while(1) {
while(r<dd&&sum<n) sum+=primenum[r++];
if(sum<n) break;
else if(sum==n) ans++;
sum-=primenum[l++];
}
printf("%d\n",ans);
}
return 0;
}