我正在为Euler问题7编写一个程序,试图找到第10001个素数。我改编了一个我已经拥有的脚本,该脚本可以找到所有数量的素数。工作正常。但是现在我有一个问题。我的代码重复了该列表。
881, 883, 887, 1, 2, 3, 5, 7, 11, 13, 17, 19
那大概是在我的代码中间。
max = int(input("What is your max no?: "))
primeList = []
while len(primeList) <= 10001:
for x in range(1, max + 1):
isPrime = True
for y in range (2 , int(x ** 0.5) + 1):
if x % y == 0:
isPrime = False
break
if isPrime:
primeList.append(x)
print(primeList)
是什么原因造成的?我应该从空白画布开始而不编辑旧脚本吗?
最佳答案
出于乐趣,我还解决了这个问题:
# Test only odd numbers because we know the only even prime is 2
oddprimes = [3]
n = 3
# when we have 10000 oddprimes we will have a total of 10001 primes: [2] + oddprimes
while len(oddprimes) < 10000:
n += 2 # advance to the next odd number
maxfactor = int(n ** 0.5) + 1
# only need to check prime factors
for prime in oddprimes:
if n % prime == 0:
# it's not prime, stop looking
break
elif prime >= maxfactor:
# if we're checking prime factors >= sqrt(n)+1 then it's prime
oddprimes.append(n)
break
print oddprimes[-1] # the 10000th odd prime which is the 10001st prime