Last active
April 17, 2022 18:27
-
-
Save md2perpe/81d1f262ca0b827b91b8e71431fcccd9 to your computer and use it in GitHub Desktop.
Prime iterator
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
import itertools | |
from typing import Iterator | |
def sift(ns: Iterator[int]) -> Iterator[int]: | |
p = next(ns) | |
yield p | |
yield from sift(filter(lambda n: n%p != 0, ns)) | |
def primes(): | |
yield from sift(itertools.count(2)) | |
def first_primes(n: int): | |
yield from (p for _, p in zip(range(n), primes())) | |
def main(): | |
print(list(first_primes(100))) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment