Back to Problems

Problem 10: Summation of Primes

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

Find the sum of all the primes below two million.

Solution Approach

At first glance, you may think of checking each number below two million individually for primality, but that would be painfully inefficient. However, we can, in fact, borrow a technique from earlier, the Sieve of Eratosthenes.

In terms of python:


limit = 2000000
sieve = [True] * limit
sieve[0:2] = [False, False]
for i in range(2, int(limit ** 0.5) + 1):
    if sieve[i]:
        sieve[i*i : limit : i] = [False] * len(range(i*i, limit, i))
    
primes = [i for i, is_prime in enumerate(sieve) if is_prime]
print(sum(primes))

Explained line by line:

Running the above code leads to an answer of $142913828922$