Skip to main content
 首页 » 编程设计

python之素数 : Why is this code giving me some composite numbers

2025年05月04日11bluestorm

我似乎得到了所有素数,但也出现了一些合数。为什么?

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]

请您参考如下方法:

因为当您在 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