为什么我的程序重复打印列表?
Why does my program repeat print lists?
我正在为欧拉计划第 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)
这是什么原因造成的?我应该从空白开始 canvas 而不是编辑旧脚本吗?
每次你找到一个质数,你就把它添加到 primeList 中,所以最后一行被要求打印一个列表。如果你想要最后一个元素,你可以:
print primeList[-1]
为了好玩我也解决了这个问题:
# 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
我正在为欧拉计划第 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)
这是什么原因造成的?我应该从空白开始 canvas 而不是编辑旧脚本吗?
每次你找到一个质数,你就把它添加到 primeList 中,所以最后一行被要求打印一个列表。如果你想要最后一个元素,你可以:
print primeList[-1]
为了好玩我也解决了这个问题:
# 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