POJ2739Sum of Consecutive Prime Numbers尺取法

来源:互联网 发布:python教学视频 编辑:程序博客网 时间:2024/05/01 11:32

一叶落寞,万物失色

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

2317412066612530

Sample Output

11230012


题目大意:一个整数可以被分为多个连续的素数的和,给定一个整数n求n可以写成多少种不同方法的连续的整数和。



思路:我的思路是先打出一个素数表来,然后进行尺取,因为要求的是连续的一段,所以我们就可以开头尾指针,用sum来统计头尾指针之间的区间和,如果说小于n,尾指针不断加,大于的话sum就减去头指针所指的数,挪动头指针、


代码:

#include <algorithm>#include <cstdio>#include <cstring>using namespace std;int read(){char ch;int s=0,f=1;ch=getchar();while(ch>'9'||ch<'0') { if(ch=='-') f*=-1;ch=getchar(); }while(ch>='0'&&ch<='9') s=s*10+ch-48,ch=getchar();return s*f;}int isprim[10005];bool pr[10005];void findprim(int n){    int k=0;    for(int i=2;i<=n;i++)    {        if(pr[i]) continue;        isprim[++k]=i;        for(int j=2;j*i<=n;j++)            pr[j*i]=true;    }}int main(){ findprim(10002); int n; while(scanf("%d",&n)==1&&n) {     int s=1,t=1;     int sum=0,ans=0;     while(1)     {        while(isprim[t]<=n&&sum<n)        {            sum+=isprim[t++];        }        if(sum==n) ans++;        sum-=isprim[s++];        if(sum<=0) break;     }     printf("%d\n",ans); } return 0;}


0 0
原创粉丝点击