【问题标题】:Prime Numbers, Sieve of Erasthosthenes , Python素数,埃拉托色尼筛法,Python
【发布时间】:2018-11-24 00:42:01
【问题描述】:

我正在开发一个程序,该程序在用户输入最大整数时在一个范围内打印可能的素数列表。基本上是Erasthothenes的筛子。

现在,这个代码块应该迭代 consecInt(一个存储 2 到该最高整数的列表的变量)的所有值并删除它们的倍数。但由于某种原因我不太明白,它只适用于第一个值。

print("                 Sieve of Erasthothenes\n    Program that generates the possible prime numbers within a given range")

n = int(input("\nEnter the highest range:   "))

def primeList(n):

    j = 2
   consecInt = [int(i) for i in range(2, n+1)]

#A = [i != False for i in range(2, n+1)]

    for i in consecInt:
        p = i
        while j <= n:
            c = j*p
            if c <= n:
                consecInt.remove(c)
             j+=1

    print(consecInt)

primeList(n)

【问题讨论】:

    标签: python-3.x iteration


    【解决方案1】:

    您应该在 for 循环的每次迭代中将 j 重置为 2。除此之外,还有其他几个错误。

    def primeList(n):
        consecInt = [int(i) for i in range(2, n+1)]
    
        for i in consecInt:
            j = 2      ## reset `j` to 2 at every iteration
            while j*i <= n:   ## it is sufficient to check `j*i <= n` rather than `j <= n`
                c = j*i
    
                if c in consecInt:    ## if `c` is NOT in consecInt, a ValueError will be raised
                    consecInt.remove(c)
    
                j += 1
    
        print(consecInt)
    
    primeList(n)
    

    【讨论】:

    • @Chi 如果您发现此答案有帮助,请考虑将其标记为已接受的答案。
    • 我该怎么做?
    • 这可能会有所帮助:stackoverflow.com/help/accepted-answer。我的答案旁边会有一个复选标记。如果您认为我的回答值得接受,请接受。
    猜你喜欢
    • 2013-10-21
    • 2011-04-25
    • 1970-01-01
    • 2011-12-16
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多