Project Euler Problem 10 – Sum for primes to 2 million
At first I attempted to solve this using the sieve code I wrote for problem 3. However that code used Python lists and was removing elements as it progressed. That was horribly inefficient. So I’ve learnt to use Python arrays, which I was surprised to learn are not a native data structure in Python. Anyway, for my reference here is the code:
import math
from array import array
def getprimes(input):
myarray = array('L',range(input))
myarray[1] = 0
for n in myarray:
if n != 0:
for j in xrange(n+n,int(input),n):
myarray[j] = 0
retvals = []
for n in myarray:
if n != 0:
retvals.append(n)
return retvals
p = getprimes(2000000)
sum = 0
for i in p:
sum += i
print sum