Skip to content

Commit f035b94

Browse files
committed
Simpler and faster is_prime() recipe.
1 parent c33b6fb commit f035b94

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

Doc/library/itertools.rst

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1104,11 +1104,6 @@ The following recipes have a more mathematical flavor:
11041104
data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
11051105
yield from iter_index(data, 1, start=3)
11061106

1107-
def is_prime(n):
1108-
"Return True if n is prime."
1109-
# is_prime(1_000_000_000_000_403) → True
1110-
return n > 1 and all(n % p for p in sieve(math.isqrt(n) + 1))
1111-
11121107
def factor(n):
11131108
"Prime factors of n."
11141109
# factor(99) → 3 3 11
@@ -1123,6 +1118,10 @@ The following recipes have a more mathematical flavor:
11231118
if n > 1:
11241119
yield n
11251120

1121+
def is_prime(n):
1122+
"Return True if n is prime."
1123+
return n > 1 and next(factor(n)) == n
1124+
11261125
def totient(n):
11271126
"Count of natural numbers up to n that are coprime to n."
11281127
# https://mathworld.wolfram.com/TotientFunction.html

0 commit comments

Comments
 (0)