POJ 2739 Sum of Consecutive Prime Numbers(Two pointers)

来源:互联网 发布:用网络漏洞怎样赚钱 编辑:程序博客网 时间:2024/05/16 19:50

【题意】给了一个数字num,问你存在多少种连续的素数之和等于这个数!

【分析】素筛+two pointers!题很简单,所以具体看代码了!

【AC代码】

#include <stdio.h>#include <assert.h>#include <string.h>#include <iostream>using namespace std;const int maxn = 10010;bool is[maxn];int a[maxn];int cnt,n;void Init(){    memset(a,0,sizeof(a));    memset(is,false,sizeof(is));    is[1]=true;    a[0] = 0;    cnt = 1;    for(int i=2; i*i<maxn; i++){        if(!is[i]){            for(int j=i*i; j<maxn; j+=i){                is[j] = true;            }        }    }    for(int i=2; i<maxn; i++){        if(!is[i]) a[cnt++] = i;    }}int main(){    Init();    while(~scanf("%d",&n)&&n){        int ans =0,sum = 0;        int l=1,r=0;        while(1){            while(sum<n&&a[r+1]<=n){                sum+=a[++r];            }            if(sum<n) break;            else if(sum>n){                sum-=a[l++];            }else if(sum==n){                ans++;                sum-=a[l++];            }        }        printf("%d\n",ans);    }    return 0;}


1 0
原创粉丝点击