Loading

POJ-2739 Sum of Consecutive Prime Numbers

Sum of Consecutive Prime Numbers

问有多少个连续的素数区间和为n

尺取模板

不用素数筛可能会T

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <functional>
#include <map>
#include <set>
#include <cmath>
#include <cstring>
#include <deque>
#include <stack>
using namespace std;
typedef long long ll;
#define pii pair<int, int>
const ll maxn = 2e5 + 10;
const ll inf = 1e17 + 10;
int p[maxn], tp = 0, prime[maxn];

void init()
{
    prime[0] = prime[1] = 1;
    for(int i=2; i*i<maxn; i++)
    {
        if(prime[i]) continue;
        for(int j=i+i; j<maxn; j+=i)
            prime[j] = 1;
    }
    for(int i=2; i<maxn; i++)
        if(prime[i] == 0)
            p[tp++] = i;
}

int main()
{
    init();
    int n;
    while(scanf("%d", &n) != EOF && n)
    {
        int now = 0, l = 0, r = 0, ans = 0;
        while(1)
        {
            while(now < n)
                now += p[r++];
            if(now == n) ans++;
            if(r -  l == 1 && now > n) break;
            now -= p[l++];
        }
        printf("%d\n", ans);
    }

    return 0;
}
posted @ 2022-05-13 01:21  dgsvygd  阅读(23)  评论(0编辑  收藏  举报