Skip to content

Instantly share code, notes, and snippets.

@zlotnleo
Created May 23, 2019 01:08
Show Gist options
  • Save zlotnleo/6ea3867475b3ca350cdebb5534e50ebd to your computer and use it in GitHub Desktop.
Save zlotnleo/6ea3867475b3ca350cdebb5534e50ebd to your computer and use it in GitHub Desktop.
Lazy Genuine Sieve of Eratosthenes in Python
import heapq
import itertools
from dataclasses import dataclass, field
def primes():
@dataclass(init=True, order=True)
class Element:
key: int = field(compare=True)
nums: any = field(compare=False)
yield 2
queue = [Element(4, itertools.count(8, 4))]
numbers = itertools.count(3, 2)
for number in numbers:
prev_min = None
while queue[0].key <= number:
cur_min = queue[0]
prev_min = heapq.heappushpop(
queue,
Element(next(cur_min.nums), cur_min.nums)
)
if not prev_min or prev_min.key != number:
num_sq = number ** 2
heapq.heappush(
queue,
Element(num_sq, itertools.count(num_sq + 2 * number, 2 * number))
)
yield number
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment