The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
我的代码:
import math
###############主程序###################
def isPrime (n):
if n==1:
return True
else:
divisor=2
end=int(math.sqrt(n))+1
while 1:
if divisor==end:
return True
else:
if n%divisor==0:
return False
else:
divisor+=1
sum=2
start=3
while start<2000000:
if isPrime(start):
sum+=start
start+=2
print sum
可是时间太长,要40多秒吧。而且代码也挺长的。牛人的代码:
marked = [0] * 2000000
value = 3
s = 2
while value < 2000000:
if marked[value] == 0:
s += value
i = value
while i < 2000000:
marked[i] = 1
i += value
value += 2
#print marked[0:100]
print s
。。又短又好,艹了,时间不到2秒。。。。好佩服啊