C - 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.
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
题意:给出一个数,求这个数是否可以由连续的素数相加得到,如果可以,求出有多少种方案,如果不行,输出0(多组输入,0为结束标志)
思路:先用素数筛,预处理出前1e5的所有素数,由于是连续的素数,所以,我们可以用尺法求是否有方案,以及方案的种数。
#include "iostream"
using namespace std;
const int Max=1e5+10;
int a[Max],is_prime[Max],prime[Max];
int main()
{
is_prime[1]=1;
for(int i=2,t=0;i<Max;i++){//线性筛
if(!is_prime[i]) prime[++t]=i;
for(int j=1;j<=t&&i*prime[j]<Max;j++){
is_prime[i*prime[j]]=1;
if(!i%prime[j]) break;
}
}
int n;
while(cin>>n&&n){
int l=0,r=0,ans=0,sum=0;//尺取
while(prime[r]<n){
r++,sum+=prime[r];//不断右移右界,直到出现sum=n或者sum>n
while(sum>n) l++,sum-=prime[l];//如果总和大于n,那么将左界往右移
if(sum==n) ans++;//如果和刚好为n,方案数加一
}
cout<<ans<<endl;
}
return 0;
}