The other day I wrote an article like this: "Primality enumeration and primality testing in Python". After publishing this, I suddenly made Python 3 for "infinite prime number generator", so I will publish it to Qiita (I think it is not practical ...)
Is the point around ʻitertools.count and
functools.partial`? The former creates an infinite stream of integers, and the latter implements partial application to methods.
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
Recommended Posts