Euler Project: Problem 10 – Python

This weeks covering of the Euler Project: Problem 10 Asks us to simply:

Find the sum of all primes below 2 million.

Were going to take almost the entire solution for this from our solution to problem 7, where we start out with a generator function to produce our prime numbers, and then use a list comprehension with sum() to answer the problem. Heres the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from itertools import takewhile
def eratosthenes():
	a = {}
	b = 2
	while 1:
		if b not in a:
			yield b
			a[b*b]=[b]
		else:
			for c in a[b]:
				a.setdefault(c+b,[]).append(c)
			del a[b]
		b+=1
 
def run():
	answer = sum(takewhile(lambda x: x < 2000000, eratosthenes()))
	print answer

To very undertsand the eratosthenes function please see Problem 7. The sum() in combination with a takewhile (which uses the lambda as a “limit”) to the generator, gives us the answer we are looking for. Nice, simple, short. Enjoy.

Comments

No Comments

Leave some