project euler 10 Summation of primes

来源:互联网 发布:mac压缩包打不开 编辑:程序博客网 时间:2024/05/16 14:17

题目:

https://projecteuler.net/problem=10

题意:

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.

求小于2000000的素数的总和

思路:

用筛选法求出素数表,然后求和就可以了,复杂度可以认为是O(nlogn),注意结果会爆int

代码:

#include <bits/stdc++.h>using namespace std;typedef long long ll;const int N = 2000000 + 10;bool is_prime[N];int prime[N];int prime_table(int n){    for(int i = 0; i < N; ++i)        is_prime[i] = true;    is_prime[0] = is_prime[1] = false;    int cnt = 0;    for(int i = 2; i < n; ++i)    {        if(is_prime[i])        {            prime[cnt++] = i;            for(int j = 2*i; j < n; j += i)                is_prime[j] = false;        }    }    return cnt;}int main(){    int cnt = prime_table(N);    ll sum = 0;    for(int i = 0; i < cnt; ++i)    {        if(prime[i] >= 2000000)            break;        sum += prime[i];    }    printf("%lld\n", sum);    return 0;}