Algorithms · Visualized
Number Theory: Modular Exponentiation
Number Theory
Divisibility, primes, hashes and modular arithmetic — the math underneath algorithms.
Computes (base^exponent) mod m efficiently, even for huge exponents, without ever calculating the full (enormous) power directly. Time: O(log exponent) average, O(log exponent) worst; space: O(1) iterative, O(log exponent) if recursive.
Big-O: GCD O(log min(a,b)); sieve O(n log log n).
Modular Exponentiation
Number TheoryComputes (base^exponent) mod m efficiently, even for huge exponents, without ever calculating the full (enormous) power directly. It combines fast exponentiation (halving the exponent each step) with taking the modulo at every multiplication to keep numbers small.
How Modular Exponentiation Works
- Initialize the result to 1, and reduce the base modulo m right away.
- While the exponent is greater than 0, check if it's odd.
- If the exponent is odd, multiply the result by the current base (mod m), then reduce the result modulo m.
- Square the base (mod m), and halve the exponent (integer division by 2) — this is the same halving trick as fast power.
- Repeat until the exponent reaches 0; the accumulated result is the final answer.
Modular Exponentiation Worked Example
Input: {base: 2, exponent: 10, mod: 1000}
result=1, base=2, exp=10. exp even: base=4, exp=5. exp odd: result=1×4=4, base=16, exp=2. exp even: base=256, exp=1. exp odd: result=4×256=1024 mod 1000=24, base=256²mod1000=536, exp=0, stop. Result: 24. (2^10=1024, 1024 mod 1000=24 — matches.)
def mod_expo(a, b, m):
a %= m
r = 1
while b > 0:
if b & 1:
r = r * a % m
a = a * a % m
b >>= 1
return rBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Modular Exponentiation Time & Space Complexity
When to Use Modular Exponentiation
- Cryptography — RSA and Diffie-Hellman key exchange both rely heavily on fast modular exponentiation with huge numbers.
- Any computation needing (base^huge_exponent) mod m, which would otherwise be computationally impossible directly.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.