UVA 1210 Sum of Consecutive Prime Numbers

https://vjudge.net/problem/UVA-1210

 

统计质数前缀和,枚举左右端点,这一段的区间和+1

 

#include<cstdio>
#define N 10001
using namespace std;
int cnt,p[N],sum[N],ans[N];
bool v[N];
int main()
{
    for(int i=2;i<N;i++)
    {
        if(!v[i])
        {
            v[i]=true;
            p[++cnt]=i;
        }
        for(int j=1;j<=cnt;j++)
        {
            if(i*p[j]>=N) break;
            v[i*p[j]]=true;
            if(i%p[j]==0) break;
        }
    }
    for(int i=1;i<=cnt;++i) sum[i]=sum[i-1]+p[i];
    for(int r=1;r<=cnt;r++)
         for(int l=r;l;l--)
         {
             if(sum[r]-sum[l-1]>=N) break;
             ans[sum[r]-sum[l-1]]++;
        }
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        if(!n) return 0;
        printf("%d\n",ans[n]);
    }
}

 

posted @ 2017-08-21 16:56  TRTTG  阅读(165)  评论(0编辑  收藏  举报