您的位置:首页 > 其它

POJ2739--Sum of Consecutive Prime Numbers(尺取法)

2015-08-16 15:37 387 查看
题目大意:给出一个数字,求共有多少个序列,使得序列和等于这个数字,序列是由连续的素数组成

分析:尺取法。先打个素数表。然后,就直接可以尺取法啦~

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;

int n, ans;
int a[10002], vis[13000];

void prime() {
int cnt = 0;
memset(vis, 0, sizeof(vis));
for(int i = 2; i <= 12000; i++) {
if(!vis[i]) {
a[cnt++] = i;
for(int j = 2*i; j <= 12000; j += i) vis[j] = 1;
}
}
return;
}

int main()
{
prime();
while(scanf("%d", &n) != EOF && n != 0) {
int s = 0, t = 0;
int sum = 0;
ans = 0;
while(true) {
while(a[t] <= n && sum < n) {
sum += a[t++];
}
if(sum == n) ans++;
sum -= a[s++];
if(s == t) t++;
if(a[s] > n) break;
}
printf("%d\n", ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: