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

Find the sum of all the primes below two million.

**Running time:** ~5 secs

**Assessment:** This solution is in C++ for some reason. Oh well. Anyway, it works fine, but like most of my other early factorization solutions, it doesn’t memoize anything, which means lots of redundant work, which makes for very long execution times. It’s pretty bad all around.

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 |
#include <iostream> #include <cmath> using namespace std; long long is_prime(long long n) { //returns 0 if not prime, 1 if prime if (n % 2 == 0) return 0; for (long long i = 3; i <= (pow(n,0.5)); i += 2) { if (n % i == 0) return 0; } return 1; } int main() { unsigned long long sum = 0; for (int i = 3; i < 2000000; i += 2) { if (is_prime(i)) { sum += i; } } cout << sum + 2; return 0; } |