编写算法以在给定范围内在Python中生成素数

时间:2016-06-06 17:58:21

标签: python algorithm primes

我看到生成素数的方法有很多种。我的代码很冗长冗余,但我知道它可以通过一些更改来压缩并减少重复性,我希望我可以指向正确的方向。基本上我想自动化我的代码中显示的过程,以便它可以适用于任何范围和所有素数。

这是我的代码:

def primes():
    multiplesList1 = []
    multiplesList2 = []
    multiplesList3 = []
    multiplesList4 = []
    multiplesList5 = []
    multiplesList6 = []
    multiplesList7 = []
    multiplesList8 = []
    multiplesList9 = []
    for i in range(2,1000):
        if i % 2 != 0 or i == 2:
            multiplesList1.append(i)
    for j in multiplesList1:
        if j % 3 != 0 or j == 3:
            multiplesList2.append(j)
    for x in multiplesList2:
        if x % 5 != 0 or x == 5:
            multiplesList3.append(x)
    for y in multiplesList3:
        if y % 11 != 0 or y == 11:
            multiplesList4.append(y)
    for z in multiplesList4:
        if z % 13 != 0 or z == 13:
            multiplesList5.append(z)
    for a in multiplesList5:
        if a % 17 != 0 or a == 17:
            multiplesList6.append(a)
    for b in multiplesList6:
        if b % 19 != 0 or b == 19:
            multiplesList7.append(b)
    for c in multiplesList7:
        if c % 23 != 0 or c == 23:
            multiplesList8.append(c)
    for d in multiplesList8:
        if d % 29 != 0 or d == 29:
            multiplesList9.append(d)
    return multiplesList9

print(primes())

1 个答案:

答案 0 :(得分:0)

您需要做的就是创建第二个for循环,其范围一直到前一个数字并检查每个模数。如果结果为0,那么它必须不是素数。

if __name__ == "__main__": 
    prime = True
    for i in range(2, 1000):
        for x in range(2, i):
            if i % x == 0:
                prime = False
        if prime:
            print(i)
        prime = True