LoginSignup
15
16

More than 5 years have passed since last update.

Python3で素数の無限ジェネレータ

Posted at

先日次のような記事を書きました: 「Pythonで素数列挙と素数判定」。これを公開したのち、ふと「素数の無限ジェネレータ」をPython3を作ったので、Qiitaに公開しておきます(実用性には乏しいと思いますが……)

ポイントはitertools.countfunctools.partialあたりでしょうか。前者は整数の無限ストリームを作り、後者はメソッド(関数)に対する部分適用を実現しています。


import itertools, functools, math

def prime_stream():
    stream = itertools.count(2)
    sieve = lambda x, y: x % y != 0

    while True:
        prime = next(stream)
        stream = filter(functools.partial(sieve, y=prime), stream)
        yield prime

if __name__ == '__main__':
    primes = prime_stream()
    for _ in range(20): print(next(primes))

# 2
# 3
# 5
# 7
# 11
# 13
# 17
# 19
# 23
# 29
# 31
# 37
# 41
# 43
# 47
# 53
# 59
# 61
# 67
# 71
15
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
16