Project Euler Problem 10: Summation of primes

Summation of primes

Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.


C++:

#include <iostream>
#include <cstring>
#include <cmath>

using namespace std;

const int MAXN = 2000000;
bool sieveflag[MAXN+1];

void esieve(int n)
{
    // 初始化
    memset(sieveflag, true, sizeof(sieveflag));

    sieveflag[0] = false;
    sieveflag[1] = false;

    for(int i=4; i<=n; i+=2)
        sieveflag[i] = false;

    // 筛选
    int max = sqrt(n);
    for(int i=3; i<=max; i+=2) {
        if(sieveflag[i]) {
            for(int j=i+i; j<=n; j+=i)
                sieveflag[j] = false;
        }
    }
}

int main()
{
    esieve(MAXN);

    int n;
    while(cin >> n && n<=MAXN) {
        long sum = 2;
        for(int i=3; i<n; i+=2)
            if(sieveflag[i])
                sum += i;
        cout << sum << endl;
    }

    return 0;
}

参考链接:Eratosthenes筛选法



原文地址:https://www.cnblogs.com/tigerisland/p/7564029.html