优选的溶液在约0.363s
完成sieve = [True] * 2000000
def mark(sieve, x):
for i in range(x+x, len(sieve), x):
sieve[i] = False
for x in range(2, int(len(sieve) ** 0.5) +1):
if sieve[x]: mark(sieve, x)
print (sum(i for i in range(2, len(sieve)) if sieve[i]))
然而,由于某种原因,我的解决方案(也是错误的)需要大约13-14秒才能执行。我很好奇是什么让我失去了太多。
val = 2000000
stop = int(floor(sqrt(val)))
print("stop: " + str(stop))
sieve = [x for x in range(2,val)]
def remove_nonprimes(sieve, p):
markset = set(sieve[p-2::p][1::])
sieve = list(filter(lambda x: x not in markset, sieve))
return sieve
for p in range(2, stop):
if(p in sieve):
sieve=remove_nonprimes(sieve, p)
print(str(sum(sieve)))