I wrote this snippet on python to resolve project Euler problem #10, but i've been waiting 15 minutes (running this code) and it still doesn't end.
Please help me to improve this code or optimize it.
Here is the snippet:
def prime (n):
f = 1 #flag
for i in range(2,n):
if n % i == 0:
f = 0
return f
s = 0 # Sum
for i in range(2,2000000):
if prime(i) == 1:
s = i + s
print s
It runs in less than 10 seconds for me.
First of all, you want to return from
prime
once you found out, that a numer is composite.Second, you do not want to check even numbers. Skip them with
xrange(3,2000000, 2)
Third, there is no need to check all numbers from
2
ton
inprime
, becausea*b = b*a
Since you use Python 2 I've replaced
range
withxrange
, it will be a little bit more efficient.