Skip to content

Commit 9120450

Browse files
Restore early-out to factor(). Strengthen tests. (GH-100591)
(cherry picked from commit c4c5790) Co-authored-by: Raymond Hettinger <[email protected]>
1 parent 95fa61c commit 9120450

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

Doc/library/itertools.rst

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -862,12 +862,14 @@ which incur interpreter overhead.
862862
"Prime factors of n."
863863
# factor(99) --> 3 3 11
864864
for prime in sieve(math.isqrt(n) + 1):
865-
while n >= prime:
865+
while True:
866866
quotient, remainder = divmod(n, prime)
867867
if remainder:
868868
break
869869
yield prime
870870
n = quotient
871+
if n == 1:
872+
return
871873
if n >= 2:
872874
yield n
873875

@@ -1256,13 +1258,21 @@ which incur interpreter overhead.
12561258
[3, 3]
12571259
>>> list(factor(10))
12581260
[2, 5]
1259-
>>> list(factor(999953*999983))
1261+
>>> list(factor(128_884_753_939)) # large prime
1262+
[128884753939]
1263+
>>> list(factor(999953 * 999983)) # large semiprime
12601264
[999953, 999983]
1261-
>>> all(math.prod(factor(n)) == n for n in range(1, 1000))
1265+
>>> list(factor(6 ** 20)) == [2] * 20 + [3] * 20 # large power
1266+
True
1267+
>>> list(factor(909_909_090_909)) # large multiterm composite
1268+
[3, 3, 7, 13, 13, 751, 113797]
1269+
>>> math.prod([3, 3, 7, 13, 13, 751, 113797])
1270+
909909090909
1271+
>>> all(math.prod(factor(n)) == n for n in range(1, 2_000))
12621272
True
1263-
>>> all(set(factor(n)) <= set(sieve(n+1)) for n in range(1, 1000))
1273+
>>> all(set(factor(n)) <= set(sieve(n+1)) for n in range(2_000))
12641274
True
1265-
>>> all(list(factor(n)) == sorted(factor(n)) for n in range(1, 1000))
1275+
>>> all(list(factor(n)) == sorted(factor(n)) for n in range(2_000))
12661276
True
12671277

12681278
>>> list(flatten([('a', 'b'), (), ('c', 'd', 'e'), ('f',), ('g', 'h', 'i')]))

0 commit comments

Comments
 (0)