Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Python 實作埃氏篩法求素數

求素數最經典的算法之一是埃拉托斯特尼篩法(埃氏篩),思路非常直觀。

先把從 2 開始的自然數排成一列:

2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

取第一個數 2,它必然是素數,再用它把序列中所有 2 的倍數篩掉:

3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

新序列的第一個數是 3,同為素數,再用它篩掉 3 的倍數:

5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

接著取 5,篩掉 5 的倍數:

7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...

如此反覆篩下去,剩下的就是全部素數。

用生成器把這個過程寫成 Python 程式碼,可以非常乾淨:

# 構造一個從 3 開始的奇數序列
def _odd_iter():
    n = 1
    while True:
        n += 2
        yield n


def _not_visible(n):
    return lambda x: x % n > 0


def primes():
    yield 2
    it = _odd_iter()
    while True:
        n = next(it)
        yield n
        it = filter(_not_visible(n), it)


for n in primes():
    if n < 1000:
        print(n)
    else:
        break

這裡的關鍵技巧是「惰性求值」:_odd_iter 只負責產生奇數,而每次找到新素數後,就用 filter 把它的倍數層層濾掉,形成一條不斷自我優化的過濾鏈,既不必預先知道上限,也不佔用額外記憶體。

Copyright © Linux教程網 All Rights Reserved