Greedy:Sum of Consecutive Prime Numbers(POJ 2739)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Greedy:Sum of Consecutive Prime Numbers(POJ 2739)相关的知识,希望对你有一定的参考价值。

                技术分享

                  素数之和

  题目大意:一些整数可以表示成一个连续素数之和,给定一个整数要你找出可以表示这一个整数的连续整数序列的个数

  方法:打表,然后用游标卡尺法即可

  

#include <iostream>
#include <functional>
#include <algorithm>
#define MAX_N 10010

using namespace std;

static int primes_set[MAX_N], flag[MAX_N], p_sum;

void inivilize(void);
void solve(const int);

int main(void)
{
    inivilize();
    int n;

    while (~scanf("%d", &n))
    {
        if (n == 0) 
            break;
        solve(n);
    }
    return EXIT_SUCCESS;
}

void solve(const int n)
{
    int s, t, sum, ans = 0;
    s = t = sum = 0;

    while (1)
    {
        while (primes_set[t] <= n && sum < n)
            sum += primes_set[t++];
        if (sum == n)
            ans++;
        if (sum < n)
            break;
        sum -= primes_set[s++];
    }
    printf("%d\n", ans);
}

void inivilize(void)
{
    int i = 2, j;

    memset(flag, 0, sizeof(flag));

    for (; i < MAX_N; i++)
    {
        if (!flag[i])
            primes_set[p_sum++] = i;
        for (j = 0; j < p_sum && primes_set[j] * i < MAX_N; j++)
            flag[primes_set[j] * i] = 1;
    }
}

技术分享

  

以上是关于Greedy:Sum of Consecutive Prime Numbers(POJ 2739)的主要内容,如果未能解决你的问题,请参考以下文章

Sum of Consecutive Prime Numbers

Sum of Consecutive Prime Numbers(poj2739)

[POJ] 2739 Sum of Consecutive Prime Numbers

Sum of Consecutive Prime Numbers POJ - 2739

Sum of Consecutive Prime Numbers(素数打表+尺取)

562. Longest Line of Consecutive One in Matrix