This does the job in ~0.7s (2.2GHz i7 quad core), but I know it can be much faster. I think learning how to speed this up could teach me a lot about Python. How do I speed this up? How do I make it more memory efficient? (without using multiprocessing and still using the sieve of eratosthenes)
from math import sqrt
import time
def sum_range(n):
A = [1 if i > 1 else 0 for i in xrange(n+1)]
for i, p in enumerate(A):
if A[i] and i <= int(sqrt(n)):
for j in xrange(i+i, n+1, i):
A[j] = 0
sum = 0
for i, p in enumerate(A):
if A[i]:
sum += i
return sum
if __name__ == '__main__':
t0 = time.time()
sum = sum_range(1000*1000*2)
t1 = time.time()
print "The sum is {} and it took {} seconds to do this".format(sum, t1-t0)
For the record this isn't a homework problem of any kind. Simply just for curiosity.