0
我正在尝试使用erathostenes筛来找到第n个素数。 是的,我看到类似的帖子,但我有这个一段代码的问题。 我想在找到第n个素数后停止算法。这是我写的:Python:找到第n个素数
def nth_prime(n):
limit = 10**2
pn = 1 #keeps track of how many prime numbers we have found
sieve = range(3, limit, 2)
top = len(sieve)
for si in sieve:
if si:
pn += 1
print pn, si #used to check while coding
if pn == n:
return si #loop breaks when the nth prime is found
else:
bottom = (si*si - 3)/2
if bottom >= top:
break
sieve[bottom::si] = [0] * -((bottom-top)//si)
print nth_prime(11)
虽然它不工作。至少不是我想要的。如果我添加回归过滤器(无,筛)[n-2]它工作正常。但我希望它停止在第n个素数的计算。 这是输出,而不是:
2 3
3 5
4 7
5 11
None
虽然我希望它继续下去,直到:
...
11 31
如果该功能能够计算所有筛到限制正确,为什么输出表现如何?