infinite sequence of primes generator in Python (unbounded Sieve of Eratosthenes)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def primes(): | |
prime_multiple_factors = {} | |
def add_factor(composite, factor): | |
if composite not in prime_multiple_factors: | |
prime_multiple_factors[composite] = set([factor]) | |
else: | |
prime_multiple_factors[composite].add(factor) | |
x = 2 | |
while True: | |
if x in prime_multiple_factors: | |
for factor in prime_multiple_factors[x]: | |
add_factor(x + factor, factor) | |
del prime_multiple_factors[x] | |
else: | |
add_factor(x * 2, x) | |
yield x | |
x += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment