2017-02-22 75 views
1

我写试图找到第一万零一主要项目欧拉的问题7的程序。我改编了一个我已经有的发现所有素数的剧本。它运行良好。但现在我有一个问题。我的代码重复列表。为什么我的程序重复打印列表?

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) 

这是什么原因造成的?我应该从一个空白的画布开始,而不是编辑一个旧的脚本?

+3

我觉得你的缩进是坏在这里... –

+0

您还对突变列表,当你使用它作为while循环中的一个条件来检查。这将产生消歧,从而产生结果。 – kaushik94

+0

对不起,我不习惯堆栈溢出代码块功能。在Python –

回答

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 
0

每次你找到一个黄金nuember将其添加到primeList,所以最后一行被要求打印的清单。如果你想最终的元素你可以:

print primeList[-1] 
相关问题