Cryptography constantly needs numbers like $a^{e} \bmod n$ with exponents hundreds of digits long. Multiplying $a$ by itself $e$ times would take longer than the age of the universe. Two ideas make it instant: reduce mod $n$ after every multiplication (allowed by modular arithmetic), and build the exponent from its binary digits.
Repeated squaring. To find $a^{e} \bmod n$:
- Write $e$ in binary, that is, as a sum of powers of 2.
- Square again and again: $a^{1}, a^{2}, a^{4}, a^{8}, \dots$, each one the square of the one before, reduced mod $n$.
- Multiply together the powers whose binary digit is 1, reducing after each multiplication.
Why it works
Worked example: A small case
- $13 = 8 + 4 + 1$ (binary $1101$).
- $5^{1} \equiv 5$, $\ 5^{2} = 25 \equiv 2$, $\ 5^{4} \equiv 2^{2} = 4$, $\ 5^{8} \equiv 4^{2} = 16$.
- $5^{13} = 5^{8} \cdot 5^{4} \cdot 5^{1} \equiv 16 \cdot 4 \cdot 5 = 320$.
- $320 = 23 \cdot 13 + 21$, so $5^{13} \equiv 21 \pmod{23}$.
Answer: $21$.
Count the work: three squarings and two multiplications, five in all, instead of the twelve multiplications of $5 \cdot 5 \cdots 5$. And no number above $22^{2} = 484$ ever appeared. (Check by brute force: $5^{13} = 1{,}220{,}703{,}125 = 23 \cdot 53{,}074{,}048 + 21$.)
Worked example: Last two digits
- We want $3^{45} \bmod 100$. $45 = 32 + 8 + 4 + 1$.
- $3^{2} = 9$, $\ 3^{4} = 81$, $\ 3^{8} \equiv 81^{2} = 6561 \equiv 61$, $\ 3^{16} \equiv 61^{2} = 3721 \equiv 21$, $\ 3^{32} \equiv 21^{2} = 441 \equiv 41$.
- $3^{45} \equiv 41 \cdot 61 \cdot 81 \cdot 3$. Step by step: $41 \cdot 61 = 2501 \equiv 1$, then $1 \cdot 81 = 81$, then $81 \cdot 3 = 243 \equiv 43$.
Answer: $43$.
Common mistake
Key idea