Binary Exponentiation
Published: Sun Feb 15 2026 | Modified: Sat Feb 07 2026 , 6 minutes reading.
Binary Exponentiation (Fast Power)
Introduction: The Trillion-Step Problem
Suppose you need to calculate (3 to the power of 1 trillion).
- Naive Loop: Multiply
3 * 3 * 3...one trillion times. This takes forever. - Binary Exponentiation: Calculate it in about 40 steps.
This algorithm is the cornerstone of modern cryptography (RSA, Diffie-Hellman), where calculating powers of massive numbers modulo a prime is the standard operation.
What Problem does it solve?
- Input: Base , Exponent , and usually a Modulo .
- Output: .
- The Promise: Calculates the result in multiplications instead of .
Core Idea (Intuition)
Use the binary representation of the exponent. . Instead of multiplying 3 ten times, we can:
- Calculate .
- Square it to get .
- Square it to get .
- Square it to get .
- Combine the parts we need ( and ) based on the binary bits of 10.
How it Works
- Initialize
result = 1. - While :
- If is odd (last bit is 1), multiply
resultby current base . - Square the base ().
- Divide by 2 (shift right).
- If is odd (last bit is 1), multiply
Typical Business Scenarios
- โ Cryptography: RSA encryption requires calculating where is huge.
- โ Matrix Powers: Calculating the -th Fibonacci number in by using matrix exponentiation.
- โ Combinatorics: Calculating Modular Inverse () for combinations .
Code Demo (TypeScript)
function modPow(base: bigint, exp: bigint, mod: bigint): bigint {
let result = 1n;
base = base % mod;
while (exp > 0n) {
// If exp is odd, multiply base with result
if (exp % 2n === 1n) {
result = (result * base) % mod;
}
// Square the base
base = (base * base) % mod;
// Divide exp by 2
exp = exp / 2n;
}
return result;
}Performance & Complexity
- Time: .
- Space: .
Summary
โBinary Exponentiation is the art of doubling. By squaring the base repeatedly, it traverses the exponent exponentially fast, turning impossible calculations into instant ones.โ
