您的位置:首页 > 其它

POJ 2739 Sum of Consecutive Prime Numbers(Two pointers)

2016-04-26 19:27 405 查看
【题意】给了一个数字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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: