Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 109+710^9+7".

What you’ll learn

  • Compute an mod ma^n \bmod m with at most 2⌊log⁡2n⌋2\lfloor\log_2 n\rfloor multiplications, prove the loop correct, and state what is known about the optimal number (addition chains).
  • Do arithmetic modulo mm safely: negative remainders, overflow, and the choice of moduli such as 109+710^9+7 and 998244353998244353.
  • 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 a2k=(ak)2a^{2k}=(a^k)^2 and a2k+1=(ak)2aa^{2k+1}=(a^k)^2a. The Optimized lesson ran it top-down by recursion; the loop below reads the bits of nn from the lowest up. Write n=∑ibi2in=\sum_ib_i2^i; then an=∏i: bi=1a2ia^n=\prod_{i:\,b_i=1}a^{2^i}, and the powers a2ia^{2^i} come from squaring again and again.

python
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 m=1m=1 return 0.

Nothing here needs numbers: repeated squaring works for any associative multiplication. It raises matrices to powers (the previous lesson), polynomials modulo χ(x)\chi(x), permutations (apply a shuffle 101810^{18} times) and functions under composition, which is the binary lifting used for jumping kk steps up a tree.

How few multiplications? Addition chains

Each step at most doubles the largest exponent so far, so ℓ(n)≥⌈log⁡2n⌉\ell(n)\ge\lceil\log_2n\rceil, and the binary method gives ℓ(n)≤⌊log⁡2n⌋+ν(n)−1\ell(n)\le\lfloor\log_2n\rfloor+\nu(n)-1. These meet for powers of two but not in general. The binary method spends 6 multiplications on x15x^{15}, through 1,2,3,6,7,14,151,2,3,6,7,14,15, while 1,2,3,6,12,151,2,3,6,12,15 needs only 5: 15 is the smallest exponent where the binary method is not optimal.

The sharp asymptotics are known. Brauer (1939) showed ℓ(n)≤log⁡2n+(1+o(1)) log⁡2n/log⁡2log⁡2n\ell(n)\le\log_2n+(1+o(1))\,\log_2n/\log_2\log_2n, by processing nn in blocks of bits (the kk-ary or window method), and Erdős (1960) showed that most nn need that many. Schönhage (1975) proved the lower bound ℓ(n)≥log⁡2n+log⁡2ν(n)−2.13\ell(n)\ge\log_2n+\log_2\nu(n)-2.13.

Predict before you look

How many multiplications, squarings included, does the left-to-right binary method use for x1000x^{1000}?

Show the answer

14

1000=111110100021000=1111101000_2 has 10 bits, six of them 1: ⌊log⁡21000⌋=9\lfloor\log_21000\rfloor=9 squarings and ν(1000)−1=5\nu(1000)-1=5 multiplications, 14 in all, against 999 for multiplying by xx repeatedly. The lower bound ⌈log⁡21000⌉=10\lceil\log_21000\rceil=10 shows that no method needs fewer than 10.

Arithmetic modulo m, safely

In modular arithmetic, a≡b(modm)a\equiv b\pmod m means that mm divides a−ba-b. Congruence respects addition, subtraction and multiplication, so you may reduce after every operation and keep all numbers below mm. Division is the exception: it needs an inverse, the subject of the next step. The choice of modulus is a design decision:

ModulusWhy it is used
109+710^9+7prime, so every nonzero residue has an inverse; a sum of two residues is below 231−12^{31}-1 (fits a signed 32-bit integer) and a product below 263−12^{63}-1 (fits a signed 64-bit integer)
998244353=119⋅223+1998244353=119\cdot2^{23}+1prime, and 2232^{23} divides p−1p-1, so it has the roots of unity that a number-theoretic transform (NTT) of length up to 2232^{23} needs
2642^{64} (unsigned overflow)reduction is free, but the modulus is not prime: even numbers have no inverse, and polynomial hashing modulo 2642^{64} is easy to attack
cpp
#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 2322^{32}, products need 128 bits: powmod(2, p - 1, p) returns 1 for the Mersenne prime p=261−1p=2^{61}-1, as Fermat's little theorem predicts.

When many multiplications share one odd modulus NN, as in cryptographic exponentiation, Montgomery multiplication (1985) avoids division altogether: it stores aa as aR mod NaR\bmod N with RR a power of two such as 2642^{64}, and replaces each reduction modulo NN 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

DerivationProof: multiplication by a permutes the residues
  1. ax≡ay(modp) ⟹ p∣a(x−y) ⟹ p∣x−y ⟹ x=yax\equiv ay\pmod p\ \Longrightarrow\ p\mid a(x-y)\ \Longrightarrow\ p\mid x-y\ \Longrightarrow\ x=y

    Let p∤ap\nmid a. The map x↦ax mod px\mapsto ax\bmod p sends {1,…,p−1}\{1,\dots,p-1\} into itself, and it is one-to-one, because pp is prime and does not divide aa:

  2. ∏x=1p−1(ax) ≡ ∏x=1p−1x(modp)⟹ap−1(p−1)! ≡ (p−1)!(modp)\prod_{x=1}^{p-1}(ax)\ \equiv\ \prod_{x=1}^{p-1}x\pmod p\qquad\Longrightarrow\qquad a^{p-1}(p-1)!\ \equiv\ (p-1)!\pmod p

    So it permutes {1,…,p−1}\{1,\dots,p-1\}, and the products over both sides agree:

  3. ap−1≡1(modp)a^{p-1}\equiv1\pmod p

    (p−1)!(p-1)! is coprime to pp, so it can be cancelled. Running the same argument over the φ(m)\varphi(m) residues coprime to mm proves Euler's theorem.

A modular inverse of aa is a bb with ab≡1(modm)ab\equiv1\pmod m. It exists exactly when gcd⁡(a,m)=1\gcd(a,m)=1: by Bézout's identity there are integers with ax+my=1ax+my=1, and then xx is the inverse. Two ways to find it:

  • Fermat, for a prime modulus: a−1≡ap−2(modp)a^{-1}\equiv a^{p-2}\pmod p, with O(log⁡p)O(\log p) multiplications. The inverse of 2 modulo 109+710^9+7 is 500000004.
  • The extended Euclidean algorithm, for any modulus, in O(log⁡m)O(\log m) steps. Python 3.8 and later also offer pow(a, -1, m).

Euler's theorem also shrinks exponents: if gcd⁡(a,m)=1\gcd(a,m)=1, then ab≡a b mod φ(m)(modm)a^b\equiv a^{\,b\bmod\varphi(m)}\pmod m. Without coprimality the general rule is ab≡a(b mod φ(m))+φ(m)(modm)a^b\equiv a^{(b\bmod\varphi(m))+\varphi(m)}\pmod m for b≥φ(m)b\ge\varphi(m), which evaluates towers like 23100 mod m2^{3^{100}}\bmod m.

python
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 5

The Chinese remainder theorem

DerivationProof, with a construction
  1. m1∣x−y, …, mk∣x−y ⟹ M∣x−ym_1\mid x-y,\ \dots,\ m_k\mid x-y\ \Longrightarrow\ M\mid x-y

    At most one solution. If xx and yy both solve the system, every mim_i divides x−yx-y, and pairwise coprime divisors multiply:

  2. x = ∑i=1kai Mi ti  mod M,Miti≡1(modmi)x\ =\ \sum_{i=1}^{k}a_i\,M_i\,t_i\ \bmod M,\qquad M_it_i\equiv1\pmod{m_i}

    A solution. Mi=M/miM_i=M/m_i is coprime to mim_i, so it has an inverse tit_i modulo mim_i. Every other MjM_j is a multiple of mim_i, so modulo mim_i only the ii-th term survives, and it equals ai⋅1a_i\cdot1:

  3. ZM ≅ Zm1×⋯×Zmk\mathbb Z_M\ \cong\ \mathbb Z_{m_1}\times\cdots\times\mathbb Z_{m_k}

    A bijection. The map from ZM\mathbb Z_M to the MM tuples is one-to-one by the first step, hence onto; sums and products can be computed componentwise.

Predict before you look

A classical puzzle from the Sunzi Suanjing: find the smallest nonnegative xx with x≡2(mod3)x\equiv2\pmod3, x≡3(mod5)x\equiv3\pmod5 and x≡2(mod7)x\equiv2\pmod7.

Show the answer

23

M=105M=105, Mi=35,21,15M_i=35,21,15 with inverses ti=2,1,1t_i=2,1,1 (since 35⋅2=70≡1(mod3)35\cdot2=70\equiv1\pmod3, and 21≡1(mod5)21\equiv1\pmod5, 15≡1(mod7)15\equiv1\pmod7). Then x=2⋅70+3⋅21+2⋅15=233≡23(mod105)x=2\cdot70+3\cdot21+2\cdot15=233\equiv23\pmod{105}. Check: 23=7⋅3+2=4⋅5+3=3⋅7+223=7\cdot3+2=4\cdot5+3=3\cdot7+2.

When the moduli share factors, x≡a1(modm1)x\equiv a_1\pmod{m_1} and x≡a2(modm2)x\equiv a_2\pmod{m_2} are solvable exactly when a1≡a2(modgcd⁡(m1,m2))a_1\equiv a_2\pmod{\gcd(m_1,m_2)}, and the solution is then unique modulo lcm⁡(m1,m2)\operatorname{lcm}(m_1,m_2); merge the congruences two at a time with the extended Euclidean algorithm. Garner's algorithm rebuilds xx 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 an mod ma^n\bmod m with at most 2⌊log⁡2n⌋2\lfloor\log_2n\rfloor multiplications; the invariant result⋅an≡AN\text{result}\cdot a^n\equiv A^N proves the loop correct, and the idea works in any associative setting.
  • Addition chains measure the true minimum: log⁡2n≤ℓ(n)≤log⁡2n+(1+o(1))log⁡2n/log⁡2log⁡2n\log_2n\le\ell(n)\le\log_2n+(1+o(1))\log_2n/\log_2\log_2n, the binary method is not optimal from n=15n=15, 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 109+710^9+7 make every nonzero residue invertible.
  • Fermat (ap−1≡1a^{p-1}\equiv1) and Euler (aφ(m)≡1a^{\varphi(m)}\equiv1) give inverses by exponentiation; the extended Euclidean algorithm gives them for any modulus, exactly when gcd⁡(a,m)=1\gcd(a,m)=1.
  • The Chinese remainder theorem makes ZM\mathbb Z_M the product of the Zmi\mathbb Z_{m_i} for pairwise coprime moduli, with the explicit solution ∑iaiMiti\sum_ia_iM_it_i.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does every addition chain for nn have length at least ⌈log⁡2n⌉\lceil\log_2 n\rceil?

  1. Because the binary method is optimal
  2. Because each step adds two earlier terms, so the largest term at most doubles per step
  3. Because nn has ⌈log⁡2n⌉\lceil\log_2 n\rceil bits that must each be read
  4. Because multiplication modulo mm takes log⁡m\log m time
Show the answer

B. Because each step adds two earlier terms, so the largest term at most doubles per step

After rr steps the largest term is at most 2r2^r, so reaching nn needs 2r≥n2^r\ge n, that is r≥log⁡2nr\ge\log_2n. The binary method is not always optimal: x15x^{15} needs 5 multiplications, not 6.

Question 2

A counting problem needs n!k! (n−k)! mod p\dfrac{n!}{k!\,(n-k)!}\bmod p with p=109+7p=10^9+7 and n≤106n\le10^6. How do you perform the divisions?

  1. Compute n! mod pn!\bmod p, k! mod pk!\bmod p and (n−k)! mod p(n-k)!\bmod p, and divide the residues as integers
  2. Use floating-point division, then round and reduce modulo pp
  3. Multiply n! mod pn!\bmod p by the inverses of k!k! and (n−k)!(n-k)! modulo pp, for example by raising them to the power p−2p-2
  4. It cannot be done: division is not defined modulo pp
Show the answer

C. Multiply n! mod pn!\bmod p by the inverses of k!k! and (n−k)!(n-k)! modulo pp, for example by raising them to the power p−2p-2

Since pp is prime and n<pn<p, the factorials are not divisible by pp, so they have inverses, and Fermat gives x−1≡xp−2(modp)x^{-1}\equiv x^{p-2}\pmod p. Precomputing all factorials and their inverses answers each query in O(1)O(1).

Question 3

In C++, long long d = (a - b) % m; with 0≤a,b<m0\le a,b<m. What can go wrong?

  1. Nothing: % always returns a value in [0,m)[0, m)
  2. d is negative when a<ba<b, because C++ truncates the quotient toward zero
  3. The subtraction overflows for every mm above 10910^9
  4. % is undefined for negative operands in C++17
Show the answer

B. d is negative when a<ba<b, because C++ truncates the quotient toward zero

For a<ba<b, a−ba-b 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 [0,m)[0,m).

Question 4

Which system has a solution?

  1. x≡1(mod4)x\equiv1\pmod4 and x≡2(mod6)x\equiv2\pmod6
  2. x≡3(mod4)x\equiv3\pmod4 and x≡0(mod6)x\equiv0\pmod6
  3. x≡2(mod4)x\equiv2\pmod4 and x≡1(mod6)x\equiv1\pmod6
  4. x≡3(mod4)x\equiv3\pmod4 and x≡5(mod6)x\equiv5\pmod6
Show the answer

D. x≡3(mod4)x\equiv3\pmod4 and x≡5(mod6)x\equiv5\pmod6

With gcd⁡(4,6)=2\gcd(4,6)=2, a solution exists exactly when the two residues agree modulo 2. Only 33 and 55 have the same parity; the solutions are x≡11(mod12)x\equiv11\pmod{12}.

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.