Why is my algorithm for finding the sum of all prime numbers below 2 million so slow? I\'m a fairly beginner programmer and this is what I came up with for finding the solution:
Nobody pointed this out, but using range
in Python 2.x is very slow. Use xrange
instaed, in this case this should give you a huge performance advantage.
See this question.
Also, you don't have to loop until the number you check, checking until round(sqrt(n)) + 1
is sufficient. (If the number greater than its square divides it, there's a number smaller than the square that you must have already noticed.)