我正在开发一个程序,该程序可以在一定范围内打印,即当用户输入最高整数时,可能的质数列表。基本上是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)
答案 0 :(得分:0)
您应该在 j
循环的每次迭代中将2
重置为for
。除此之外,还有其他一些错误。
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)