Skip to content

Commit aef019b

Browse files
[3.12] Improve the sieve() recipe in the itertools docs (gh-109199) (#109203)
Improve the sieve() recipe in the itertools docs (gh-109199) Lazier sieve (cherry picked from commit d3ed992) Co-authored-by: Raymond Hettinger <[email protected]>
1 parent 888bcf4 commit aef019b

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

Doc/library/itertools.rst

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1030,13 +1030,16 @@ The following recipes have a more mathematical flavor:
10301030
def sieve(n):
10311031
"Primes less than n."
10321032
# sieve(30) --> 2 3 5 7 11 13 17 19 23 29
1033+
if n > 2:
1034+
yield 2
1035+
start = 3
10331036
data = bytearray((0, 1)) * (n // 2)
1034-
data[:3] = 0, 0, 0
10351037
limit = math.isqrt(n) + 1
1036-
for p in compress(range(limit), data):
1038+
for p in iter_index(data, 1, start, limit):
1039+
yield from iter_index(data, 1, start, p*p)
10371040
data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
1038-
data[2] = 1
1039-
return iter_index(data, 1) if n > 2 else iter([])
1041+
start = p*p
1042+
yield from iter_index(data, 1, start)
10401043

10411044
def factor(n):
10421045
"Prime factors of n."

0 commit comments

Comments
 (0)