Modular exponentiation computes base^exp mod m — and this tool does it the
right way, with the fast square-and-multiply algorithm, so even thousand-digit
exponents resolve instantly. It is the workhorse behind RSA, Diffie-Hellman, and
primality tests.
How it works
Naively computing base^exp first is impossible for large exponents — the
number is too big to store. Instead, the modulus is applied after every step:
result = 1
b = base mod m
while exp > 0:
if exp is odd: result = (result × b) mod m
b = (b × b) mod m # square
exp = exp >> 1 # next bit
Because every intermediate value stays below m², and the loop runs only about
log2(exp) times, the answer is found extremely quickly regardless of how large
the exponent is.
Example and tips
(7^256) mod 13 is computed in just 8 squaring steps and equals 9, even
though 7^256 itself has 217 digits. A modulus of 1 always yields 0, since
every integer is divisible by 1. Keep the exponent non-negative — negative
powers would require a modular inverse, which is a different operation.