您的位置:首页 > 其它

project euler 10 Summation of primes

2017-12-16 13:35 447 查看

题目:

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
;
int prime
;

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"
9e90
, sum);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: