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.

#include 
#include 
#include 
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.

Comments are closed.