我似乎得到了所有素数,但一些复合数字也出现了。为什么呢?
p=[2,]
while len(p)<35:
next = p[-1]+1
for i in range(len(p)):
if next%p[i]==0:
next+=1
i=0
p.append(next)
print p
这是我得到的输出:
[2,3,5,7,11,13,16,17,19,23,27,29,31,35,37,41,43,47,50,53,59,61,65, 67,71,73,77,79,83,87,89,95,97,101,103]
答案 0 :(得分:7)
因为当您在for循环中更新next
时,您没有从主要列表的开头进行扫描,以检查新的next
是否可以被整除。您可以尝试以下方式。
p=[2,]
number=3
while len(p)<35:
if all(number%i!=0 for i in p):
p.append(number)
number += 1
print p
答案 1 :(得分:1)
如果在每次迭代中打印i
的值,您将看到问题。 i
的值将继续增加。
Test 3 divided by 2 (p[0]) Test 4 divided by 2 (p[0]) Test 5 divided by 3 (p[1]) Test 6 divided by 2 (p[0]) Test 7 divided by 3 (p[1]) Test 7 divided by 5 (p[2]) Test 8 divided by 2 (p[0]) Test 9 divided by 3 (p[1]) Test 10 divided by 5 (p[2]) Test 11 divided by 7 (p[3]) Test 12 divided by 2 (p[0]) Test 13 divided by 3 (p[1]) Test 13 divided by 5 (p[2]) Test 13 divided by 7 (p[3]) Test 13 divided by 11 (p[4]) Test 14 divided by 2 (p[0]) Test 15 divided by 3 (p[1]) Test 16 divided by 5 (p[2]) Test 16 divided by 7 (p[3]) Test 16 divided by 11 (p[4]) Test 16 divided by 13 (p[5]) Test 17 divided by 2 (p[0])
每次代码评估行for i in range(len(p))
时,它都不会考虑i
的当前值,因为range(len(p))
实际上是一个列表(或Python 3中的生成器),所以它只迭代列表,而不是像你期望的那样实际做i = i+1
。
例如,考虑len(p)=3
时的情况。然后range(len(p))
将等同于[0,1,2]
。 for循环首先取值0
。然后,下一次迭代将具有值1
,第三次将具有值2
,无论您对循环体内i
的值如何操作。
一种解决方案不是使用for i in range(len(p))
,而是自己进行迭代:
next = p[-1]+1 # actually you can do next = next+1
i = 0
while i < len(p):
if next%p[i]==0:
next += 1
i=0
else:
i+=1
p.append(next)