Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22882

Shannon -jj Behrens: Python: Streaming Sieve of Eratosthenes

$
0
0

I thought of a cute way of infinitely generating prime numbers that I call the Streaming Sieve of Eratosthenes:

#!/usr/bin/env python3

"""
Streaming Sieve of Eratosthenes

I thought of a cute way of infinitely generating prime numbers.
"""

from collections import defaultdict


# upcoming is a defaultdict. Each key is an upcoming number. Each value is a list
# of prime factors of that number.
upcoming = defaultdict(list)

n = 2
while True:
factors = upcoming[n]
del upcoming[n]
if not factors:
print(n) # Prime
factors.append(n)
for factor in factors:
next_n = n + factor
upcoming[next_n].append(factor)
n += 1

Viewing all articles
Browse latest Browse all 22882

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>