"""Fast (binary) exponentiation.

Idea
----
To compute a^n, look at n in binary. a^13 = a^8 * a^4 * a^1 because
13 = 0b1101. Square the base each step and multiply it into the result when
the current bit is 1. With a modulus, reduce after every multiplication so
numbers stay small. Python's built-in ``pow(a, n, m)`` does the same thing.

Complexity
----------
Time:  O(log n) multiplications
Space: O(1)
"""


def fast_power(base: int, exponent: int, modulus: int | None = None) -> int:
    """Return ``base ** exponent`` (optionally mod ``modulus``)."""
    if exponent < 0:
        raise ValueError("exponent must be non-negative")
    result = 1
    if modulus is not None:
        if modulus == 1:
            return 0
        base %= modulus
    while exponent:
        if exponent & 1:
            result = result * base if modulus is None else result * base % modulus
        base = base * base if modulus is None else base * base % modulus
        exponent >>= 1
    return result
