def generate_primes(n):
"""generate_primes(n) -> list
Returns a list of all primes <= n."""
from math import sqrt
primes = [2]
potentialPrimes = []
for x in range(3, n + 1):
potentialPrimes.append(x)
if x % 2 == 0:
potentialPrimes.remove(x)
currentPrime = potentialPrimes[0]
primes.append(currentPrime)
while currentPrime < sqrt(n):
for x in potentialPrimes:
if x % currentPrime == 0:
potentialPrimes.remove(x)
currentPrime = potentialPrimes[0]
for x in potentialPrimes:
primes.append(x)
print(primes)
generate_primes(100)
当我尝试调用该函数时,它会打印出来:
[2, 3, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
知道为什么吗? 任何改进我的代码的方法都会受到高度赞赏。
答案 0 :(得分:1)
在while循环中你设置currentPrime = 5但是不要从潜在的素数中删除它,所以在下一次迭代中potentialPrimes [0]仍然是5.而5%5 == 0所以它将它从潜在的素数中移除并且做同样的7。
这是相同风格的代码,但正确显示了所有数字
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
答案 1 :(得分:0)
在迭代时从列表中删除项目绝不是一个好主意
for x in potentialPrimes:
if x % currentPrime == 0:
potentialPrimes.remove(x)