"""Miller-Rabin primality test (deterministic for 64-bit integers).

Idea
----
Write n - 1 = d * 2^s with d odd. For a prime n, Fermat's little theorem and
the fact that 1 has only the square roots +1 and -1 mod a prime mean that for
every base a, either a^d = 1 (mod n) or a^(d * 2^r) = -1 (mod n) for some
r < s. A base that breaks this is a *witness* that n is composite.

For random bases each round catches a composite with probability at least
3/4. For n < 3.3 * 10^24 the first 13 primes as bases are known to be enough,
so this implementation is deterministic for every 64-bit integer.

Complexity
----------
Time:  O(k log^3 n) for k bases with schoolbook multiplication
Space: O(1)

When to use
-----------
Large numbers where trial division (O(sqrt n)) is far too slow, for example
checking 18-digit numbers or generating primes for hashing.
"""

BASES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41)


def is_probable_prime(n: int) -> bool:
    if n < 2:
        return False
    for p in BASES:
        if n % p == 0:
            return n == p
    d, s = n - 1, 0
    while d % 2 == 0:
        d //= 2
        s += 1
    for a in BASES:
        x = pow(a, d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True
