Fast power: xⁿ in O(log n)
x¹³ = x⁸ · x⁴ · x¹: square x repeatedly and multiply in the squares where n's binary has a 1. With a mod, it also gives modular inverses.
The idea
Multiplying x by itself n times is . Instead write n in binary: 13 = 1101₂ = 8 + 4 + 1, so x¹³ = x⁸ · x⁴ · x¹. Squaring gives x, x², x⁴, x⁸… in log n steps; multiply in the ones you need.
With a modulus p, Fermat's little theorem gives division: a⁻¹ ≡ a^(p−2) mod p. That's how you compute nCr mod 10⁹ + 7.
Worked example
3¹³
- 13 = 1101 in binary. Squares: 3¹ = 3, 3² = 9, 3⁴ = 81, 3⁸ = 6,561.
- Bits set for 1, 4 and 8 → 3 × 81 × 6,561 = 1,594,323.
- 4 squarings instead of 12 multiplications.
Pseudocode
The steps in plain words. ← means “set to”; indentation shows what's inside what.
See it run
The worked example, step by step, beside the Python. The highlighted line is the one running.
Step-by-step
3¹³
Solution · Pythonline 2
def power(x, n, mod=None):result = 1while n > 0:if n & 1: # this bit is set: use the current squareresult = result * x if mod is None else result * x % modx = x * x if mod is None else x * x % modn >>= 1return result def inverse(a, p=10**9 + 7): # p must be primereturn power(a, p - 2, p) # Python's built-in pow(x, n, mod) does the same.Step 1 of 9· line 2
13 in binary is 1101: 13 = 8 + 4 + 1. So 3¹³ = 3⁸ × 3⁴ × 3¹. Keep squaring x (3, 3², 3⁴, 3⁸…) and multiply in the ones whose bit is set.
multiplications.
How to spot it
- Pow(x, n), huge exponents, “mod 10⁹+7” with division, powers for fast .
Common mistakes
- Negative exponents: compute power(1/x, −n).
- Using a ** b % m in Python for huge b: pow(a, b, m) is far faster.
Practise the ideas first
One small exercise per idea, right in the editor, before the problems below.
Where it comes up
Go further
Up next for you · Beginner
“Have I seen this?” is a set →