Python 3.x 试图从1-n生成素数,但始终缺少素数3和5。?
知道为什么吗?Python 3.x 试图从1-n生成素数,但始终缺少素数3和5。?,python-3.x,primes,Python 3.x,Primes,知道为什么吗? 任何改进我的代码的方法都会非常感激。在迭代时从列表中删除项目从来都不是一个好主意 [2, 3, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] 在while循环中设置currentPrime=5,但不要将其从潜在素数中移除,所以在下一次迭代中,潜在素数[0]仍然是5。5%5==0,所以它从潜在的素数中去掉它,对7也一样 下面是相同样式的代码,但正确显示了所有数
任何改进我的代码的方法都会非常感激。在迭代时从列表中删除项目从来都不是一个好主意
[2, 3, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
在while循环中设置currentPrime=5,但不要将其从潜在素数中移除,所以在下一次迭代中,潜在素数[0]仍然是5。5%5==0,所以它从潜在的素数中去掉它,对7也一样 下面是相同样式的代码,但正确显示了所有数字
for x in potentialPrimes:
if x % currentPrime == 0:
potentialPrimes.remove(x)
def生成素数(n):
从数学导入sqrt
素数=[]
潜在素数=范围(2,n+1)
素数=潜在素数[0]
虽然素数这段代码是一个非常奇怪的混合朴素计算和埃拉托斯筛。你需要下定决心。所以,如果我只移动primes.append(currentPrime)到while循环的第一行,就可以了?不,在两个地方仍然有一些值。那是1。第二,你们不应该迭代一个列表,并且在循环体中修改相同的列表。(迭代列表的副本)。3-你为什么不使用一些众所周知的方法来寻找素数呢?对于这一点,已经有了非常有效和简单的算法,这些算法是由比我聪明得多的人完成的,可能是你和大多数人类。1。有点困惑你所说的“两个地方的一些价值”2。我不知道你所说的列表上的iterate是什么意思,它们都在循环体中修改了同一个ist。“正如你所看到的,我对这些东西不太了解。3.如果我只是使用一种众所周知的方法,我就不会学到很多东西。
for x in potentialPrimes:
if x % currentPrime == 0:
potentialPrimes.remove(x)
def generate_primes(n):
from math import sqrt
primes=[]
potentialPrimes=range(2,n+1)
prime=potentialPrimes[0]
while prime<sqrt(n):
primes.append(prime)
potentialPrimes.remove(prime)
for potential in potentialPrimes:
if potential%prime==0:
potentialPrimes.remove(potential)
prime=potentialPrimes[0]
for potential in potentialPrimes:
primes.append(potential)
for number in primes:
print number