Algorithm, Data structure/Solved Algorithmic Problem

Project Euler #10 - Summation of primes

JaykayChoi 2016. 6. 12. 20:40

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

Find the sum of all the primes below two million.


출처: https://projecteuler.net/



2,000,000 이하 소수의 합을 구하는 문제입니다.

앞전 문제와 마찬가지로 Eratosthenes' sieve 을 이용해 소수들을 구하는 방법으로 풀었습니다.




my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
typedef long long ll;
 
bool isPrime[10000000];
int maxNum = 2000000;
 
void eratosthenes()
{
    memset(isPrime, 1sizeof(isPrime));
 
    isPrime[0= isPrime[1= false;
 
    int sqrtn = int(sqrt(maxNum));
 
    for (int i = 2; i <= sqrtn; i++)
    {
        if (isPrime[i])
        {
            for (int j = i*i; j <= maxNum; j += i)
                isPrime[j] = false;
        }
    }
}
 
 
int main() 
{
    const int limit = 2000000;
    ll ret = 0;
    eratosthenes();
 
    for (int i = 2; i <= limit; i++)
    {
        if (isPrime[i])
        {
            ret += i;
        }
    }
 
    cout << ret << endl;
 
    system("pause");
    return 0;
}
cs