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