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]
知道为什么吗?任何改进我的代码的方法也将不胜感激。