### Project Euler Problem 10 Statement

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

Find the sum of all the primes below two million.

### Solution

#### A simple approach

Using the function `prime_sieve(N)`

, introduced in Project Euler Problem 7, to find prime numbers less than N, we can solve this problem in less than 100ms using a couple lines of Python:

```
from Euler import prime_sieve
print (sum(prime_sieve(2000000)))
```

#### A more extensible solution

HackerRank poses a more demanding problem by having us find the sum of primes *not greater than* (same as *less than or equal to*) `N`, where 1 ≤ `N` ≤ 10^{6} for up to 10,000 queries.

Using the sieve of Eratosthenes and considering only odd indexes, each new zero element we encounter is a prime number. We add this prime to our sum and use slicing, `a[start:stop:step]`

, to set all its multiples to −1. The choice for −1 was arbitrary and was selected because it stands out.

The statement `primeSum[i::i] = [−1]*(N//i)`

fills every `step`

index of the list, starting from `start`

to the end of the list^{1} with −1; our value to indicate non-prime numbers.

Next, we replace the index with the prime number sum, `s`

. We do the same for the following even index since it can’t be prime. This allows each query to act as an index to the appropriate sum in the list `primeSum[]`

.

^{1}When `stop`

is omitted, as it is in this case, it fills to the end of the list

#### A step–by–step breakdown of this algorithm

There’s a lot going on with the few lines of code in this algorithm. The table below illustrates the method for `N`=10 and `s`=2.

primeSum[] listiprimeSum[i]==0? s [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

3 Y 5 [0, 0, 2, −1, 0, 0, −1, 0, 0, −1, 0] primeSum[3],[4] = s [0, 0, 2, 5, 5, 0, −1, 0, 0, −1, 0] 5 Y 10 [0, 0, 2, 5, 5, −1, −1, 0, 0, −1, −1] primeSum[5],[6] = s [0, 0, 2, 5, 5, 10, 10, 0, 0, −1, −1] 7 Y 17 [0, 0, 2, 5, 5, 10, 10, −1, 0, −1, −1] primeSum[7],[8] = s [0, 0, 2, 5, 5, 10, 10, 17, 17, −1, −1] 9 N 17 [ all multiples of 9 already set by multiples of 3 ] primeSum[9],[10]= s [0, 0, 2, 5, 5, 10, 10, 17, 17, 17, 17]

Now, we have a one–to–one list mapping queries to sums of prime numbers. For example, `primeSum[10]`

= 17, the sum of all prime numbers not greater than 10.

#### HackerRank version

HackerRank asks us to run up to 10,000 test cases and sum prime numbers not greater than *N*, where 1 ≤ *N* ≤ 10^{6}.

### Python Source Code

```
s = 2; N = 2000000; primeSum = [0]*(N+1)
primeSum[2] = s
for i in range(3, N, 2):
if primeSum[i]==0:
s+= i
primeSum[i::i] = [-1]*(N//i)
primeSum[i] = s; primeSum[i+1] = s #each odd index and the following even index
L = int(input("Sum of primes not greater than? "))
print ("is", primeSum[L])
```

### Last Word

Have a look at the `prime_sieve()`

function listed in Common Functions and Routines for Project Euler.