TExcelTAD
Home › Selected Topics: FFT, Strings, Parallelism & NP-Completeness › Modular Exponentiation and Its Bit Cost

Modular Exponentiation and Its Bit Cost

Primality tests, RSA, Diffie-Hellman and the number-theoretic transform all compute powers ab mod na^b \bmod n with exponents of hundreds or thousands of bits. Multiplying by aa a total of b−1b - 1 times is hopeless: for a 1024-bit bb that is about 1030810^{308} multiplications. Repeated squaring needs fewer than 2lg⁡b2\lg b modular multiplications. This lesson states the algorithm, counts its multiplications exactly and turns that count into a bit-operation bound. The number theory around it (Fermat's and Euler's theorems, orders) is in Fast Exponentiation of Number Theory & Cryptography.

Square and multiply

Write the exponent in binary, b=⟨bβ−1bβ−2⋯b0⟩b = \langle b_{\beta-1} b_{\beta-2} \cdots b_0 \rangle with bβ−1=1b_{\beta-1} = 1. Reading the bits from the most significant one, keep d=ac mod nd = a^{c} \bmod n, where cc is the number formed by the bits read so far. Reading one more bit doubles cc (square dd) and, if the bit is 1, adds one (multiply dd by aa):

text
MODULAR-EXPONENTIATION(a, b, n)    // left to right; returns a^b mod n
1  d = 1
2  for i = beta - 1 downto 0        // the bits of b, most significant first
3      d = d * d mod n               // c = 2c
4      if b_i == 1
5          d = d * a mod n           // c = c + 1
6  return d

The loop invariant is d=ac mod nd = a^c \bmod n for the prefix cc of the exponent; at the end c=bc = b. The program traces it on 7560 mod 5617^{560} \bmod 561, a value that appears again in Miller-Rabin (561=3⋅11⋅17561 = 3 \cdot 11 \cdot 17 is a Carmichael number).

python · try it yourself
def mod_exp_trace(a, b, n):
    d, c = 1, 0
    print(f"b = {b} = {b:b} in binary")
    print(" bit   c      d = a^c mod n")
    for bit in f"{b:b}":
        d, c = d * d % n, 2 * c
        if bit == "1":
            d, c = d * a % n, c + 1
        print(f"  {bit}  {c:4}   {d:4}")
    return d

result = mod_exp_trace(7, 560, 561)
print("7^560 mod 561 =", result, " Python's pow:", pow(7, 560, 561))
b = 560 = 1000110000 in binary
 bit   c      d = a^c mod n
  1     1      7
  0     2     49
  0     4    157
  0     8    526
  1    17    160
  1    35    241
  0    70    298
  0   140    166
  0   280     67
  0   560      1
7^560 mod 561 = 1  Python's pow: 1

Counting multiplications

With d=1d = 1 at the start, the first squaring and multiplication are trivial, so a careful implementation starts with d=ad = a after the leading bit. Then it does exactly β−1\beta - 1 squarings and one multiplication for every 1 bit after the leading one:

#multiplications=(β−1)+(ν(b)−1),\#\text{multiplications} = (\beta - 1) + (\nu(b) - 1),

where ν(b)\nu(b) is the number of 1 bits of bb. That is between β−1\beta - 1 (for a power of 2) and 2(β−1)2(\beta - 1) (for 2β−12^\beta - 1), and about 1.5β1.5\beta for a random exponent. The right-to-left variant computes the same count by squaring aa repeatedly and multiplying the result by those squares a2ia^{2^i} whose bit bib_i is 1.

python · try it yourself
import random

def mod_exp_count(a, b, n):
    """left to right, starting after the leading bit; returns (a^b mod n, multiplications)"""
    bits = f"{b:b}"
    d, mults = a % n, 0
    for bit in bits[1:]:
        d = d * d % n; mults += 1
        if bit == "1":
            d = d * a % n; mults += 1
    return d, mults

def right_to_left(a, b, n):
    result, square, mults = 1, a % n, 0
    while b:
        if b & 1:
            result = result * square % n; mults += 1
        b >>= 1
        if b:
            square = square * square % n; mults += 1
    return result, mults

n = 2**61 - 1
for b in [16, 15, 560, 2**20, 2**20 - 1, 10**18]:
    v1, m1 = mod_exp_count(3, b, n)
    v2, m2 = right_to_left(3, b, n)
    beta, ones = b.bit_length(), bin(b).count("1")
    print(f"b = {b:>20}: {beta:2} bits, {ones:2} ones, {m1:3} multiplications "
          f"(formula {beta - 1 + ones - 1:3}); right to left {m2:3}; values agree {v1 == v2 == pow(3, b, n)}")

rng = random.Random(9)
avg = sum(mod_exp_count(3, rng.getrandbits(1024) | 1 << 1023, n)[1] for _ in range(100)) / 100
print(f"random 1024-bit exponents: {avg:.1f} multiplications on average (about 1.5 * 1024 = 1536)")
b =                   16:  5 bits,  1 ones,   4 multiplications (formula   4); right to left   5; values agree True
b =                   15:  4 bits,  4 ones,   6 multiplications (formula   6); right to left   7; values agree True
b =                  560: 10 bits,  3 ones,  11 multiplications (formula  11); right to left  12; values agree True
b =              1048576: 21 bits,  1 ones,  20 multiplications (formula  20); right to left  21; values agree True
b =              1048575: 20 bits, 20 ones,  38 multiplications (formula  38); right to left  39; values agree True
b =  1000000000000000000: 60 bits, 24 ones,  82 multiplications (formula  82); right to left  83; values agree True
random 1024-bit exponents: 1531.7 multiplications on average (about 1.5 * 1024 = 1536)

(The right-to-left count is one higher, because its first multiplication, by the initial result 1, is not skipped.)

Bit cost

Each modular multiplication of β\beta-bit numbers is a multiplication producing 2β2\beta bits and a division by nn. With schoolbook arithmetic both cost O(β2)O(\beta^2) bit operations. If aa, bb and nn all have β\beta bits, there are O(β)O(\beta) multiplications, so

T(β)=O(β)⋅O(β2)=O(β3) bit operations.T(\beta) = O(\beta) \cdot O(\beta^2) = O(\beta^3) \text{ bit operations}.

With Karatsuba multiplication the bound drops to O(β1+lg⁡3)≈O(β2.58)O(\beta^{1 + \lg 3}) \approx O(\beta^{2.58}), and with FFT-based multiplication (The Inverse FFT and Fast Polynomial Multiplication) to O(β2lg⁡β)O(\beta^2 \lg \beta). Real libraries use Montgomery multiplication, which replaces the division by nn with shifts, and sliding windows, which handle several exponent bits per multiplication and cut the non-squaring multiplications from about β/2\beta/2 to roughly β/w\beta/w for windows of ww bits.

The cubic growth is visible in practice: doubling the key size of RSA makes each private-key operation roughly eight times slower. The program estimates the schoolbook cost with machine words of 64 bits: a modular multiplication of kk-word numbers costs about 2k22k^2 word multiplications (multiply, then reduce).

python · try it yourself
def word_cost(bits, word=64):
    k = -(-bits // word)                          # words per number
    mults = 1.5 * bits                            # modular multiplications for a typical exponent
    return mults * 2 * k * k

base = word_cost(1024)
print(" modulus bits   word multiplications   relative to 1024 bits")
for bits in [1024, 2048, 3072, 4096, 8192]:
    w = word_cost(bits)
    print(f"{bits:13} {w:22,.0f} {w / base:20.1f}")
 modulus bits   word multiplications   relative to 1024 bits
         1024                786,432                  1.0
         2048              6,291,456                  8.0
         3072             21,233,664                 27.0
         4096             50,331,648                 64.0
         8192            402,653,184                512.0

In C++

power_mod in C++ for moduli below 2322^{32}, so that every product fits in 64 bits. (Larger moduli need 128-bit products or a big-number library.)

cpp · try it yourself
#include <cstdint>
#include <cstdio>

uint64_t power_mod(uint64_t a, uint64_t b, uint64_t m, int& mults) {
    uint64_t result = 1 % m, square = a % m;
    mults = 0;
    while (b > 0) {
        if (b & 1) { result = result * square % m; mults++; }
        b >>= 1;
        if (b > 0) { square = square * square % m; mults++; }
    }
    return result;
}

int main() {
    int mults;
    struct Case { uint64_t a, b, m; } cases[] = {
        {7, 560, 561}, {2, 1000000006, 1000000007}, {3, 4294967290ULL, 4294967291ULL}, {12345, 0, 97}};
    for (auto [a, b, m] : cases) {
        uint64_t r = power_mod(a, b, m, mults);
        std::printf("%llu^%llu mod %llu = %llu  (%d multiplications)\n",
                    (unsigned long long)a, (unsigned long long)b, (unsigned long long)m, (unsigned long long)r, mults);
    }
}
7^560 mod 561 = 1  (12 multiplications)
2^1000000006 mod 1000000007 = 1  (44 multiplications)
3^4294967290 mod 4294967291 = 1  (61 multiplications)
12345^0 mod 97 = 1  (0 multiplications)

The second and third lines are Fermat tests: 1 000 000 0071\,000\,000\,007 and 4 294 967 291=232−54\,294\,967\,291 = 2^{32} - 5 are primes, so ap−1≡1(modp)a^{p-1} \equiv 1 \pmod p. Practise with Fast Modular Exponentiation.

Test yourself

How many modular multiplications does left-to-right square-and-multiply use for b=210b = 2^{10} (starting with d=ad = a after the leading bit)?

  1. 10
  2. 11
  3. 20
  4. 1023

What is the loop invariant of left-to-right exponentiation?

  1. d=aid = a^i
  2. d=ac mod nd = a^c \bmod n, where cc is the number formed by the exponent bits read so far
  3. dd is always smaller than aa
  4. d=b mod nd = b \bmod n

With schoolbook arithmetic, how many bit operations does computing ab mod na^b \bmod n take when all three numbers have β\beta bits?

  1. O(β)O(\beta)
  2. O(β2)O(\beta^2)
  3. O(β3)O(\beta^3)
  4. O(2β)O(2^\beta)

Roughly how much slower is a 4096-bit modular exponentiation than a 2048-bit one with schoolbook arithmetic?

  1. 2 times
  2. 4 times
  3. 8 times
  4. 16 times