Skip to content

Instantly share code, notes, and snippets.

@wjandrea
Last active January 17, 2022 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wjandrea/6322ed8906ef3780311a39b5bcc88825 to your computer and use it in GitHub Desktop.
Save wjandrea/6322ed8906ef3780311a39b5bcc88825 to your computer and use it in GitHub Desktop.
"sieve" iterative, not recursive, based on https://www.youtube.com/watch?v=5jwV3zxXc8E
def sieve(s):
seen = []
for i in s:
if any(i%n == 0 for n in seen): # If "i" is divisible by any previous numbers
continue
yield i
seen.append(i)
from itertools import count # Don't reinvent the wheel ("nats")
s = sieve(count(2))
for i, x in zip(range(15), s): # Get first 15 results
print(i, x)
"""
Output:
0 2
1 3
2 5
3 7
4 11
5 13
6 17
7 19
8 23
9 29
10 31
11 37
12 41
13 43
14 47
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment