Modular Exponentiation and Its Bit Cost
Primality tests, RSA, Diffie-Hellman and the number-theoretic transform all compute powers with exponents of hundreds or thousands of bits. Multiplying by a total of times is hopeless: for a 1024-bit that is about multiplications. Repeated squaring needs fewer than 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, with . Reading the bits from the most significant one, keep , where is the number formed by the bits read so far. Reading one more bit doubles (square ) and, if the bit is 1, adds one (multiply by ):
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 dThe loop invariant is for the prefix of the exponent; at the end . The program traces it on , a value that appears again in Miller-Rabin ( is a Carmichael number).
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 at the start, the first squaring and multiplication are trivial, so a careful implementation starts with after the leading bit. Then it does exactly squarings and one multiplication for every 1 bit after the leading one:
where is the number of 1 bits of . That is between (for a power of 2) and (for ), and about for a random exponent. The right-to-left variant computes the same count by squaring repeatedly and multiplying the result by those squares whose bit is 1.
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 -bit numbers is a multiplication producing bits and a division by . With schoolbook arithmetic both cost bit operations. If , and all have bits, there are multiplications, so
With Karatsuba multiplication the bound drops to , and with FFT-based multiplication (The Inverse FFT and Fast Polynomial Multiplication) to . Real libraries use Montgomery multiplication, which replaces the division by with shifts, and sliding windows, which handle several exponent bits per multiplication and cut the non-squaring multiplications from about to roughly for windows of 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 -word numbers costs about word multiplications (multiply, then reduce).
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 , so that every product fits in 64 bits. (Larger moduli need 128-bit products or a big-number library.)
#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: and are primes, so . Practise with Fast Modular Exponentiation.
Test yourself
How many modular multiplications does left-to-right square-and-multiply use for (starting with after the leading bit)?
- 10
- 11
- 20
- 1023
What is the loop invariant of left-to-right exponentiation?
- , where is the number formed by the exponent bits read so far
- is always smaller than
With schoolbook arithmetic, how many bit operations does computing take when all three numbers have bits?
Roughly how much slower is a 4096-bit modular exponentiation than a 2048-bit one with schoolbook arithmetic?
- 2 times
- 4 times
- 8 times
- 16 times