问题是找到第 1000 个素数。我为此编写了以下python代码。问题是,我得到了第 10、第 20 素数的正确答案,但之后每增加 10 就会使我偏离目标。我在这里无法捕捉到错误:(
count=1 #to keep count of prime numbers
primes=() #tuple to hold primes
candidate=3 #variable to test for primes
while count<20:
for x in range(2,candidate):
if candidate%x==0:
candidate=candidate+2
else : pass
primes=primes+(candidate,)
candidate=candidate+2
count=count+1
print primes
print "20th prime is ", primes[-1]
如果您想知道,count 被初始化为 1,因为我没有测试 2 作为素数(我从 3 开始)并且candidate
递增 2,因为只有奇数可以是素数。我知道还有其他方法可以解决这个问题,例如素数定理,但我想知道这种方法有什么问题。另外,如果您有任何优化想法,请提出建议。
谢谢你