Fast Exponentiation
In short: write the exponent in binary and square-and-multiply computes base**exp % mod in O(log exp) time and O(1) extra space — one squaring of the base per bit, and one
extra multiply into the accumulator wherever that bit is 1. That turns a cost that grows
with the exponent's value into one that grows with its digit count, which is the
difference between instant and 30,000 years for an exponent like 10¹⁸. The same loop
works for anything associative you can multiply: numbers, matrices, permutations.

Later in the course Quarry gets a text index, and its core is a rolling hash. The
hash is a number computed from a window of characters, updated in O(1) as the window
slides one character to the right. To drop the character leaving on the left, the hash
needs B**(k-1) % p, where B is the hash base, k the window length and p a large
prime. Checksums, id scramblers and the modular inverses in the next lesson all need the
same thing: a big power, reduced modulo something, computed quickly.
Python has it built in, as pow(base, exp, mod). This lesson is about how it works,
because the idea behind it isn't really about numbers. It's about reading the
exponent's bits, and it applies to anything you can multiply: matrices, permutations,
functions. The interview corner computes the 10¹⁸th Fibonacci number with it.
Multiplying e times is too slow
The obvious loop multiplies e times:
For e = 45 that's fine. For e = 10**18, a perfectly ordinary exponent in hashing
and cryptography, it would take 30,000 years at a billion multiplications per second.
The loop's cost grows with the value of the exponent. We want it to grow with the
number of digits in the exponent.