Summation of primes

Problem 10

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

Find the sum of all the primes below two million.


In [1]:
from euler import gen_prime, gen_lt

In [2]:
from itertools import islice, takewhile

In [3]:
# 20130725 version ported to Python 3
list(zip(gen_prime(), range(6)))[-1][0]


Out[3]:
13

In [4]:
p = list(islice(gen_prime(), 6))
p[-1], p


Out[4]:
(13, [2, 3, 5, 7, 11, 13])

In [5]:
# 20130725 version
list(gen_lt(gen_prime(), 20))


Out[5]:
[2, 3, 5, 7, 11, 13, 17, 19]

In [6]:
list(takewhile(lambda x: x < 20, gen_prime()))


Out[6]:
[2, 3, 5, 7, 11, 13, 17, 19]

In [7]:
def foo(n):
    return sum(gen_lt(gen_prime(), n))

In [8]:
n = 10
foo(n)


Out[8]:
17

In [9]:
n = 2000000

In [10]:
%timeit foo(n)
foo(n)


The slowest run took 169.45 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 42.9 ms per loop
Out[10]:
142913828922

In [11]:
def foo(n):
    return sum(takewhile(lambda x: x < n, gen_prime()))

In [12]:
%timeit foo(n)
foo(n)


10 loops, best of 3: 47.9 ms per loop
Out[12]:
142913828922