def all_primes(start,end):
list_nonprimes = []
list_primes = []
for i in range(start,end):
for a in range(2,i):
if i % a == 1 and i not in list_nonprimes:
if i not in list_primes:
list_primes.append(i)
else:
list_nonprimes.append(i)
return list_primes
为什么这会给我一个不正确的输出?
>>> all_primes(1,10)
[3,5,7,9]
如何消除9?
答案 0 :(得分:4)
有一种更简单的方法可以做到这一点,因为您已经固有地生成了少于您当前正在检查的数字的素数列表:
def all_primes(start,end):
list_primes = []
for i in range(2,end):
for a in list_primes:
if i % a == 0:
break
else:
list_primes.append(i)
return [x for x in list_primes if x >= start]
理解这一点的关键是了解for...else
构造在Python中的工作原理。从本质上讲,for
循环可以有else
语句,只有在循环评估期间没有运行break
语句时才会执行该语句。
答案 1 :(得分:0)
从以下位置更改:
if i % a == 1 and i not in list_nonprimes:
if i not in list_primes:
list_primes.append(i)
else:
list_nonprimes.append(i)
为:
if i % a == 0 and i not in list_primes:
if i not in list_nonprimes:
list_nonprimes.append(i)
else:
list_primes.append(i)
除此之外:您还可以考虑实施Sieve of Eratosthenes。理解并且效率更高,这是非常直接的。
答案 2 :(得分:0)
我尝试检查你的代码,看看你哪里出错了,但最后做了一些改变和优化。我对代码进行了评论,希望它能够解释自己。
def all_primes(start,end):
list_nonprimes = []
list_primes = []
for i in range(start,end):
# if already present in non_primes, skip
if i in list_nonprimes: continue
# if already present in primes, skip
if i in list_primes: continue
# if 2, mark it as prime. Special case
if i == 2 :
list_primes.append(i)
continue
# even numbers are not prime
if i%2 == 0:
list_nonprimes.append(i)
continue
# only check divisibility with odd numbers starting at 3
# and ending at sqrt(i)
for a in range(3,int(i**0,5)+1,2):
if i % a == 0 :
list_nonprimes.append(i)
break
# if we got here, and the number wasn;t added to non_primes
# it must be a prime
if i not in list_nonprimes: list_primes.append(i)
return list_primes
start = 2
end = 10
print all_primes(start, end)