Skip to content

Instantly share code, notes, and snippets.

@pawelrubin
Last active March 21, 2021 14:38
Show Gist options
  • Save pawelrubin/4d259fffaf8b9cad3cd47a9fce8f447d to your computer and use it in GitHub Desktop.
Save pawelrubin/4d259fffaf8b9cad3cd47a9fce8f447d to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes Python implementation - recursive approach using iterators
from typing import Iterator
def sieve(n: int) -> Iterator[int]:
def _sieve(xs: Iterator[int]) -> Iterator[int]:
if head := next(xs, None):
yield head
yield from _sieve(x for x in xs if x % head != 0)
return _sieve(iter(range(2, n + 1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment