Sub topic 14
Modular Exponentiation for Large Numbers
This chapter assumes you have read the previous chapters on exponentiation by squaring and negative exponents. It also assumes you are comfortable with Python's % (remainder) and // (integer division) operators and with Big-O notation. The goal here is to compute values like 3^200 mod 13, or 7^(10^18) mod 1,000,000,007, without ever building the full power.
Why the Full Power Is a Problem
Exponentiation by squaring makes only O(log n) multiplications, but it says nothing about how large the numbers being multiplied get. The value x^n has about n · log10(x) digits. Python integers have arbitrary precision, so the code will not overflow. It will slow down, though, because multiplying two k-digit numbers costs much more than O(1).
big = 3 ** 200
print(len(str(big))) # 96
print(big % 13) # 9A 96-digit number is still manageable. With an exponent of 10^18, the result would have about 4.8 × 10^17 digits, which no computer can store. In languages with fixed-width integers, such as C, Java, or Rust, the trouble starts much sooner: a 64-bit integer overflows once the value passes about 9.2 × 10^18.
Many applications only need the remainder. These include cryptography (RSA, Diffie–Hellman), primality tests, hashing, and the "answer modulo 10^9 + 7" convention in programming contests. Modular exponentiation computes x^n mod m directly and keeps every intermediate value smaller than m.
The Identity That Makes It Work
Remainders pass through multiplication:
(a · b) mod m = ((a mod m) · (b mod m)) mod m
So you can reduce any product modulo m as soon as you compute it, and the final remainder comes out the same. This means each step of exponentiation by squaring can be reduced:
- If n is even: x^n mod m = (h · h) mod m, where h = x^(n//2) mod m.
- If n is odd: x^n mod m = (h · h · x) mod m, reducing after each multiplication.
- Base case: x^0 mod m = 1 mod m.
Every value of h is smaller than m, so every product is smaller than m². The size of the numbers you handle depends on m, not on n.
The Recursive Implementation
def mod_power(x, n, m):
if n == 0:
return 1 % m
half = mod_power(x, n // 2, m)
result = (half * half) % m
if n % 2 == 1:
result = (result * x) % m
return result
print(mod_power(3, 200, 13)) # 9
print(pow(3, 200, 13)) # 9This has the same structure as fast_power from the previous chapter, with three changes:
- The base case returns
1 % minstead of1. This matters only whenm == 1. Every integer is congruent to 0 modulo 1, so the correct answer is 0, while a barereturn 1would be wrong. - Each multiplication is followed by
% m. - The odd case reduces after squaring and then again after multiplying by
x. This keeps every intermediate value below m² (strictly, below m · max(m, |x|)).
Python's built-in three-argument pow(x, n, m) does the same job in C and is the version to use in production code. Writing your own is still worthwhile. It shows what pow is doing, and you will need it in languages without a built-in.
Tracing 3^200 mod 13
The recursion halves n at each call: 200 → 100 → 50 → 25 → 12 → 6 → 3 → 1 → 0. That is 9 calls, about log2(200) + 1. The results are computed as the calls return, from the bottom of the stack up.
| n | half (from call with n // 2) | (half · half) mod 13 | n odd? | result |
|---|---|---|---|---|
| 0 | none (base case) | none | no | 1 |
| 1 | 1 | 1 | yes: 1 · 3 mod 13 | 3 |
| 3 | 3 | 9 | yes: 9 · 3 = 27 mod 13 | 1 |
| 6 | 1 | 1 | no | 1 |
| 12 | 1 | 1 | no | 1 |
| 25 | 1 | 1 | yes: 1 · 3 mod 13 | 3 |
| 50 | 3 | 9 | no | 9 |
| 100 | 9 | 81 mod 13 = 3 | no | 3 |
| 200 | 3 | 9 | no | 9 |
No intermediate value goes above 81. The direct computation needed a 96-digit number.
You can check the answer by hand: 3^3 = 27 ≡ 1 (mod 13), and 200 = 3 · 66 + 2, so 3^200 ≡ 3^2 = 9.
Cost Analysis
The recursion makes floor(log2 n) + 2 calls when n ≥ 1. Each call does at most two modular multiplications. If m fits in a machine word, each multiplication costs O(1), so the total is O(log n) time. For n = 10^18 that is about 60 levels and at most about 120 multiplications.
When m itself is large, as with 2048-bit RSA moduli, each multiplication costs roughly O(k²) for k-digit operands with schoolbook multiplication. The total is then O(log n · k²). The point is that k is the size of m and stays fixed no matter how large n gets.
The recursion depth is also O(log n). That is far below Python's default limit of 1000 frames, so the stack overflow problems from the chapter on depth limits do not come up here. An exponent would need more than 2^990 to come close.
An Iterative Version
Some languages, and some environments such as embedded systems or GPU kernels, discourage recursion. The same algorithm can run as a loop that reads the bits of n from least significant to most significant:
def mod_power_iter(x, n, m):
result = 1 % m
base = x % m
while n > 0:
if n & 1:
result = (result * base) % m
base = (base * base) % m
n >>= 1
return result
print(mod_power_iter(3, 200, 13)) # 9
print(mod_power_iter(7, 10**18, 1_000_000_007) == pow(7, 10**18, 1_000_000_007)) # Truebase holds x^(2^i) mod m at bit i. Whenever bit i of n is 1, that factor is multiplied into result. The loop runs the same number of multiplications as the recursive version and uses O(1) extra space.
Edge Cases and Gotchas
Modulus of 1 or less
m == 1: both versions return 0, which is correct because of1 % m.m == 0:% 0raisesZeroDivisionError. That is reasonable, since "mod 0" is not defined here.m < 0: Python's%returns results with the sign of m, so you get non-positive remainders. Most callers never mean this. Validatem > 0at your API boundary.
Negative base
In Python, -2 % 5 is 3, so a negative x gives a correct non-negative answer as long as m > 0. In C, C++, Java, and Go, % keeps the sign of the dividend, so -2 % 5 is -2. When porting this code, normalize first with ((x % m) + m) % m.
Negative exponents
The fast_power approach of taking 1 / ... does not work in modular arithmetic. Fractions do not exist modulo m. You need a modular inverse instead: a value y with x · y ≡ 1 (mod m). This exists only when gcd(x, m) = 1. Python 3.8+ computes it with pow(x, -1, m):
def mod_power_signed(x, n, m):
if n < 0:
inv = pow(x, -1, m) # ValueError if x has no inverse mod m
return mod_power(inv, -n, m)
return mod_power(x, n, m)
print(mod_power_signed(3, -2, 7)) # 4, because 3**2 = 9 ≡ 2 and 2 * 4 = 8 ≡ 1 (mod 7)Overflow in fixed-width languages
Reducing after every multiplication keeps values below m. However, the product half * half can still reach about m² before the reduction. With 64-bit integers, m must be below about 3 × 10^9 for that product to fit. That is why contest moduli such as 10^9 + 7 are chosen. For larger m, use 128-bit intermediates or a "mulmod" routine. Python has no such limit.
Reducing the exponent
Reducing n modulo m is wrong in general. Exponents follow a different rule: if gcd(x, m) = 1, then n can be reduced modulo φ(m), Euler's totient. This is a separate theorem, not the identity used above. Mixing the two up is a common bug.
A Practical Use: The Fermat Primality Test
Fermat's little theorem says that if p is prime and a is not divisible by p, then a^(p−1) ≡ 1 (mod p). A composite number usually fails this check for a random a. This gives a fast probabilistic test, and it relies completely on modular exponentiation because p − 1 can have hundreds of digits.
import random
def probably_prime(p, trials=20):
if p < 4:
return p in (2, 3)
for _ in range(trials):
a = random.randrange(2, p - 1)
if mod_power(a, p - 1, p) != 1:
return False
return True
print(probably_prime(1_000_000_007)) # True
print(probably_prime(1_000_000_008)) # FalseExercises
Exercise
What does mod_power(5, 0, 1) return, and what would it return if the base case were "return 1"? Which answer is correct?
Show answer
It returns 1 % 1 = 0. With "return 1" it would return 1. The correct answer is 0, because every integer is congruent to 0 modulo 1.
Exercise
How many recursive calls does mod_power(x, 1000, m) make, including the base case? List the values of n.
Show answer
11 calls: n = 1000, 500, 250, 125, 62, 31, 15, 7, 3, 1, 0. That is floor(log2 1000) + 2 = 9 + 2 = 11.
Exercise
Compute 2^10 mod 7 by hand with the squaring recursion, showing the value returned at each level.
Show answer
n=0 returns 1. n=1: 1·1=1, odd, 1·2=2. n=2: 2·2=4. n=5: 4·4=16 mod 7=2, odd, 2·2=4. n=10: 4·4=16 mod 7=2. The answer is 2. Check: 1024 = 7·146 + 2.
Exercise
A colleague computes pow(3, 106 % 13, 13) to speed up pow(3, 106, 13). Is the result correct? Explain.
Show answer
Not in general. Exponents may be reduced modulo phi(13) = 12, not modulo 13. Here 106 % 12 = 4, so the true answer is 3^4 mod 13 = 81 mod 13 = 3. 106 % 13 = 1, so the colleague gets 3^1 mod 13 = 3. The answers match only by coincidence, because 3 has order 3 modulo 13 and both 4 and 1 leave remainder 1 when divided by 3. The method is still wrong in general.