@@ -829,6 +829,11 @@ and :term:`generators <generator>` which incur interpreter overhead.
829829 "Returns the sequence elements n times."
830830 return chain.from_iterable(repeat(tuple(iterable), n))
831831
832+ def loops(n):
833+ "Loop n times. Like range(n) but without creating integers."
834+ # for _ in loops(100): ...
835+ return repeat(None, n)
836+
832837 def tail(n, iterable):
833838 "Return an iterator over the last n items."
834839 # tail(3, 'ABCDEFG') → E F G
@@ -1060,6 +1065,11 @@ The following recipes have a more mathematical flavor:
10601065 data[p*p : n : p+p] = bytes(len(range(p*p, n, p+p)))
10611066 yield from iter_index(data, 1, start=3)
10621067
1068+ def is_prime(n):
1069+ "Return True if n is prime."
1070+ # is_prime(1_000_000_000_000_403) → True
1071+ return n > 1 and all(n % p for p in sieve(math.isqrt(n) + 1))
1072+
10631073 def factor(n):
10641074 "Prime factors of n."
10651075 # factor(99) → 3 3 11
@@ -1165,6 +1175,17 @@ The following recipes have a more mathematical flavor:
11651175 >>> list (islice(tabulate(lambda x : 2 * x), 4 ))
11661176 [0, 2, 4, 6]
11671177
1178+
1179+ >>> for _ in loops(5 ):
1180+ ... print (' hi' )
1181+ ...
1182+ hi
1183+ hi
1184+ hi
1185+ hi
1186+ hi
1187+
1188+
11681189 >>> list (tail(3 , ' ABCDEFG' ))
11691190 ['E', 'F', 'G']
11701191 >>> # Verify the input is consumed greedily
@@ -1424,6 +1445,24 @@ The following recipes have a more mathematical flavor:
14241445 >>> set (sieve(10_000 )).isdisjoint(carmichael)
14251446 True
14261447
1448+
1449+ >>> small_primes = [2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ]
1450+ >>> list (filter (is_prime, range (- 100 , 100 ))) == small_primes
1451+ True
1452+ >>> carmichael = {561 , 1105 , 1729 , 2465 , 2821 , 6601 , 8911 } # https://oeis.org/A002997
1453+ >>> any (map (is_prime, carmichael))
1454+ False
1455+ >>> # https://www.wolframalpha.com/input?i=is+128884753939+prime
1456+ >>> is_prime(128_884_753_939 ) # large prime
1457+ True
1458+ >>> is_prime(999953 * 999983 ) # large semiprime
1459+ False
1460+ >>> is_prime(1_000_000_000_000_007 ) # factor() example
1461+ False
1462+ >>> is_prime(1_000_000_000_000_403 ) # factor() example
1463+ True
1464+
1465+
14271466 >>> list (factor(99 )) # Code example 1
14281467 [3, 3, 11]
14291468 >>> list (factor(1_000_000_000_000_007 )) # Code example 2
0 commit comments