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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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 |