Author
Result
1.1389 s
Code
def is_prime(n):
"""Return True iff n is prime.
Works for arbitrarily-large ints (uses deterministic Miller-Rabin with
bases that are proven complete for every 64-bit input, and then
additional bases for bigger numbers)."""
# Handle tiny inputs quickly.
if n < 2:
return False
small = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
for p in small:
if n % p == 0:
return n == p
# Decompose n-1 as d * 2^s
d, s = n - 1, 0
while d % 2 == 0:
d //= 2
s += 1
def _try(a):
"""Miller-Rabin witness loop for base a."""
x = pow(a, d, n)
if x == 1 or x == n - 1:
return False
for _ in range(s - 1):
x = pow(x, 2, n)
if x == n - 1:
return False
return True # composite
# Bases that make the test deterministic for every 64-bit number
bases64 = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37)
if n < 341550071728321: # < 3.4e14
bases = (2, 3, 5, 7, 11, 13, 17)
elif n < 3825123056546413051: # < 3.8e18
bases = (2, 3, 5, 7, 11, 13, 17, 19, 23)
else: # full 64-bit range
bases = bases64
for a in bases:
if _try(a):
return False
return True
# ------------------------------------------------------------------
# Quick self-test (executed only when this file is run directly).
# ------------------------------------------------------------------
if __name__ == "__main__":
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, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,
317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,
503, 509, 521, 523, 541
}
# Exhaustive test up to 541
for x in range(max(small_primes) + 1):
assert is_prime(x) == (x in small_primes)
# Two big-integer assertions from the statement
assert is_prime(50944352050432840594664327703654217607483249127368282443658421370320240418632150463386971396202568194925235923024411275631368759242814890471657334733218208416824863730606520908198845521423439226153813263186188880157525787115965153854071772222183528102751911)
assert not is_prime(270232216891381492844952749373617571683872847618266214418525494195836938837070446176769548415673569982361014481475276843062714955758548211652446400421420170897612445799329432093790003911616167788064934840566031517914337645532465618728202484917009287562085840204296939771978314429077070675423479)
print("All tests passed.")