Sum of Consecutive Prime Numbers POJ - 2739(尺取)

在这里插入图片描述

简单的尺取题, 拿来练手咯, 顺便复习一波欧拉筛

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const LL maxn = 1e4+10;

int primeNum[maxn];
bool isPrime[maxn];
void getPrime(int n)
{   //筛法求n以内所有素数
    for(int i = 0; i < maxn; i++)
        isPrime[i] = true;
    for(int i = 2; i <= n; i++)
        if(isPrime[i])
            for(int j = 2; i*j <= n; j++)
                isPrime[i*j] = false;
    for(int i = 2, j = 1; i <= n; i++)
        if(isPrime[i])
            primeNum[j++] = i;
}
int main()
{
    int n;
    getPrime(maxn-10);
    while(cin >> n && n){
        //尺取
        int cnt = 0, i = 1, j = 1, sum = 0;
        if(isPrime[n]) cnt++;
        while(1){
            while(sum<n && primeNum[j]<n)
                sum += primeNum[j++];
            if(sum < n) break;
            if(sum == n) cnt++;
            sum -= primeNum[i++];
        }
        cout << cnt << endl;
    }

	return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/86755238