POJ 2739 Sum of Consecutive Prime Numbers

Sum of Consecutive Prime Numbers
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 13616   Accepted: 7590

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

Source

//求素数序列中求连续的和为给定数值的子序列有几个
//蛮好的一道题目、素数筛选+队列实现
//先把10000以内的素数求出来,然后依次进队,并用一个变量记录队列里面的素数和,与给的值进行比较
//每个数进出各一次、时间复杂度为 O(n);
#include
<iostream> #include <stdio.h> #include <string.h> #include <algorithm> #include <cmath> #include <queue> using namespace std; bool b[10000]; bool ip(int n) { int i,m=sqrt(double(n)); for(i=2;i<=m;i++) if(n%i==0) return 0; return 1; } int r[3000]; int main() { int i,j,n,m; for(i=2+2;i<=10000;i+=2) b[i]=1; for(i=3;i<10000;i+=2) if(ip(i)) for(j=i*2;j<10000;j+=i) b[j]=1; j=0; for(i=2;i<=10000;i++) if(!b[i]) r[j++]=i; n=j; int sum,t; while(scanf("%d",&m),m) { queue<int>Q; sum=t=0; for(i=0;i<n;i++) { Q.push(r[i]); sum+=r[i]; if(sum==m) { t++; sum-=Q.front(); Q.pop(); } while(sum>m) { sum-=Q.front(); Q.pop(); if(sum==m) { t++; sum-=Q.front(); Q.pop(); break; } } if(Q.empty()) break; } printf("%d\n",t); } return 0; }

你可能感兴趣的:(number)