这个问题是找到第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是因为只有奇数才可能是质数。我知道还有其他解决这个问题的方法,比如质数定理,但我想知道这种方法的问题在哪里。如果你有任何优化建议,请提出。
谢谢