Fast Exponentiation & Modular Arithmetic
Repeated squaring, modular inverses, Fermat’s little theorem and the Chinese remainder theorem.
RSA encryption raises numbers hundreds of digits long to powers hundreds of digits long, modulo other such numbers, in about a millisecond. Done naively that would take more multiplications than there are atoms in the universe; by repeated squaring it takes a few thousand. This lesson builds the toolkit behind it, and behind every "answer modulo ".
What you’ll learn
- Compute with at most multiplications, prove the loop correct, and state what is known about the optimal number (addition chains).
- Do arithmetic modulo safely: negative remainders, overflow, and the choice of moduli such as and .
- Prove Fermat's little theorem and Euler's theorem, and compute modular inverses by Fermat or by the extended Euclidean algorithm.
- Prove the Chinese remainder theorem constructively and use it to combine residues.
Repeated squaring, as a loop
Fast exponentiation rests on and . The Optimized lesson ran it top-down by recursion; the loop below reads the bits of from the lowest up. Write ; then , and the powers come from squaring again and again.
def power_mod(a, n, m):
"""a**n % m with O(log n) multiplications (right-to-left binary method)."""
result = 1 % m
a %= m
while n > 0:
if n & 1: # this bit of n is set: multiply its power in
result = result * a % m
a = a * a % m # a now holds the original a^(2^(i+1))
n >>= 1
return result
print(power_mod(2, 10, 1000)) # 24
print(power_mod(3, 200, 10**9 + 7)) # 136318165, same as pow(3, 200, 10**9 + 7)Python's built-in pow(a, n, m) does the same. Starting with 1 % m makes return 0.
Nothing here needs numbers: repeated squaring works for any associative multiplication. It raises matrices to powers (the previous lesson), polynomials modulo , permutations (apply a shuffle times) and functions under composition, which is the binary lifting used for jumping steps up a tree.
How few multiplications? Addition chains
Each step at most doubles the largest exponent so far, so , and the binary method gives . These meet for powers of two but not in general. The binary method spends 6 multiplications on , through , while needs only 5: 15 is the smallest exponent where the binary method is not optimal.
The sharp asymptotics are known. Brauer (1939) showed , by processing in blocks of bits (the -ary or window method), and Erdős (1960) showed that most need that many. Schönhage (1975) proved the lower bound .
How many multiplications, squarings included, does the left-to-right binary method use for ?
Show the answer
14
has 10 bits, six of them 1: squarings and multiplications, 14 in all, against 999 for multiplying by repeatedly. The lower bound shows that no method needs fewer than 10.
Arithmetic modulo m, safely
In modular arithmetic, means that divides . Congruence respects addition, subtraction and multiplication, so you may reduce after every operation and keep all numbers below . Division is the exception: it needs an inverse, the subject of the next step. The choice of modulus is a design decision:
| Modulus | Why it is used |
|---|---|
| prime, so every nonzero residue has an inverse; a sum of two residues is below (fits a signed 32-bit integer) and a product below (fits a signed 64-bit integer) | |
| prime, and divides , so it has the roots of unity that a number-theoretic transform (NTT) of length up to needs | |
| (unsigned overflow) | reduction is free, but the modulus is not prime: even numbers have no inverse, and polynomial hashing modulo is easy to attack |
#include <cstdint>
using u64 = std::uint64_t;
using u128 = unsigned __int128; // GCC/Clang extension, not standard C++
u64 mulmod(u64 a, u64 b, u64 m) { // (a * b) % m without overflow, any m < 2^64
return (u64)((u128)a * b % m);
}
u64 powmod(u64 a, u64 n, u64 m) { // a^n % m with O(log n) multiplications
u64 result = 1 % m;
a %= m;
while (n > 0) {
if (n & 1) result = mulmod(result, a, m);
a = mulmod(a, a, m);
n >>= 1;
}
return result;
}For moduli above , products need 128 bits: powmod(2, p - 1, p) returns 1 for the Mersenne prime , as Fermat's little theorem predicts.
When many multiplications share one odd modulus , as in cryptographic exponentiation, Montgomery multiplication (1985) avoids division altogether: it stores as with a power of two such as , and replaces each reduction modulo by two multiplications and a shift. The conversion costs something once, so it pays off only over many operations.
Inverses: Fermat, Euler and Bézout
Let . The map sends into itself, and it is one-to-one, because is prime and does not divide :
So it permutes , and the products over both sides agree:
is coprime to , so it can be cancelled. Running the same argument over the residues coprime to proves Euler's theorem.
A modular inverse of is a with . It exists exactly when : by Bézout's identity there are integers with , and then is the inverse. Two ways to find it:
- Fermat, for a prime modulus: , with multiplications. The inverse of 2 modulo is 500000004.
- The extended Euclidean algorithm, for any modulus, in steps. Python 3.8 and later also offer
pow(a, -1, m).
Euler's theorem also shrinks exponents: if , then . Without coprimality the general rule is for , which evaluates towers like .
def ext_gcd(a, b):
"""Return (g, x, y) with a*x + b*y == g == gcd(a, b)."""
if b == 0:
return (a, 1, 0)
g, x, y = ext_gcd(b, a % b)
return (g, y, x - (a // b) * y)
def inverse(a, m):
g, x, _ = ext_gcd(a % m, m)
if g != 1:
raise ValueError("no inverse: gcd(a, m) != 1")
return x % m
print(inverse(3, 7), pow(3, 7 - 2, 7)) # 5 5The Chinese remainder theorem
At most one solution. If and both solve the system, every divides , and pairwise coprime divisors multiply:
A solution. is coprime to , so it has an inverse modulo . Every other is a multiple of , so modulo only the -th term survives, and it equals :
A bijection. The map from to the tuples is one-to-one by the first step, hence onto; sums and products can be computed componentwise.
A classical puzzle from the Sunzi Suanjing: find the smallest nonnegative with , and .
Show the answer
23
, with inverses (since , and , ). Then . Check: .
When the moduli share factors, and are solvable exactly when , and the solution is then unique modulo ; merge the congruences two at a time with the extended Euclidean algorithm. Garner's algorithm rebuilds digit by digit in a mixed radix, avoiding huge intermediate numbers.
The Chinese remainder theorem lets you compute modulo several small numbers instead of one big one. RSA decryption works modulo the two secret primes separately and recombines, about four times faster than working modulo their product. Exact convolutions with large coefficients are computed by NTTs modulo three primes and reassembled by the theorem.
Key takeaways
- Repeated squaring computes with at most multiplications; the invariant proves the loop correct, and the idea works in any associative setting.
- Addition chains measure the true minimum: , the binary method is not optimal from , and the Scholz conjecture is open.
- Reduce after every operation, keep products within 64 bits (or use 128-bit products or Montgomery form), and normalize negative remainders in C++. Primes like make every nonzero residue invertible.
- Fermat () and Euler () give inverses by exponentiation; the extended Euclidean algorithm gives them for any modulus, exactly when .
- The Chinese remainder theorem makes the product of the for pairwise coprime moduli, with the explicit solution .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does every addition chain for have length at least ?
- Because the binary method is optimal
- Because each step adds two earlier terms, so the largest term at most doubles per step
- Because has bits that must each be read
- Because multiplication modulo takes time
Show the answer
B. Because each step adds two earlier terms, so the largest term at most doubles per step
After steps the largest term is at most , so reaching needs , that is . The binary method is not always optimal: needs 5 multiplications, not 6.
A counting problem needs with and . How do you perform the divisions?
- Compute , and , and divide the residues as integers
- Use floating-point division, then round and reduce modulo
- Multiply by the inverses of and modulo , for example by raising them to the power
- It cannot be done: division is not defined modulo
Show the answer
C. Multiply by the inverses of and modulo , for example by raising them to the power
Since is prime and , the factorials are not divisible by , so they have inverses, and Fermat gives . Precomputing all factorials and their inverses answers each query in .
In C++, long long d = (a - b) % m; with . What can go wrong?
- Nothing:
%always returns a value in dis negative when , because C++ truncates the quotient toward zero- The subtraction overflows for every above
%is undefined for negative operands in C++17
Show the answer
B. d is negative when , because C++ truncates the quotient toward zero
For , is negative and so is the remainder: -7 % 3 == -1. Write ((a - b) % m + m) % m, or simply (a - b + m) % m when both are already reduced. Python's % would return a value in .
Which system has a solution?
- and
- and
- and
- and
Show the answer
D. and
With , a solution exists exactly when the two residues agree modulo 2. Only and have the same parity; the solutions are .
Further reading
- D. E. Knuth, The Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd ed. (Addison-Wesley, 1997), §4.6.3, "Evaluation of Powers".
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 31.
- P. L. Montgomery, "Modular multiplication without trial division," Mathematics of Computation 44(170) (1985), 519–521.
- R. L. Rivest, A. Shamir & L. Adleman, "A method for obtaining digital signatures and public-key cryptosystems," Communications of the ACM 21(2) (1978), 120–126.