Infinite prime number generator in Python3

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

Infinite prime number generator in Python3
Prime number 2 in Python
Project Euler # 7 "1000 1st prime number" in Python
Zundokokiyoshi (generator) in Python
Prime numbers in Python
Prime number enumeration and primality test in Python
[Python 3] Prime factorization in 14 lines
I made a prime number generation program in Python
I made a prime number generation program in Python 2
Number recognition in images with Python
random French number generator with python
Prime number
Prime number generation program by Python
Prime number enumeration in one line
Infinite product in Python (using functools)
Study, number guessing game in Python
A program that determines whether a number entered in Python is a prime number
I searched for prime numbers in python
Project Euler # 17 "Number of Characters" in Python
Quadtree in Python --2
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Natural number generator
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
[Python] Generator function
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python