11 Jun 2011 maragato   » (Master)

Euler 10 in C++

The other night I took on Project Euler’s problem #10. The problem statement went like this:

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

Find the sum of all the primes below two million.

I went with Python and you can find the result here. I just rewrote the exact same algorithm using C++ and Boost, just for fun.

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
#include <iostream>
#include <cmath>
#include <boost/dynamic_bitset.hpp>
using namespace std;
 
unsigned long long prime_sum(int limit)
{
        if (limit < 2) return 0;
 
        long sieve_size = ceil(limit / 2);
        boost::dynamic_bitset<> sieve(sieve_size);
        unsigned long long sum = 2;
 
        sieve.flip();
 
        for (unsigned int i = 0; i < floor(sqrt(limit) / 2); i++) {
                if (!sieve[i])
                        continue;
                for (int j = (i * (i + 3) * 2) + 3; j < sieve_size; j += (i * 2) + 3)
                        sieve[j] = 0;
        }
 
        for (unsigned int i = 0; i < sieve_size; i++)
                if (sieve[i])
                        sum += (i * 2) + 3;
 
        return sum;
}
 
 
int main(void)
{
        cout << prime_sum(2000000) << endl;
        return 0;
}

Runs in 0.019s.

Syndicated 2010-08-06 15:46:32 from Roberto Teixeira's blog

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!