Technique
Binary Exponentiation (fast power)
Compute a^n (mod m) in O(log n) by squaring and multiplying on set bits; generalises to matrices and any associative operation.
0%
mastery
0/9 solved
0/9 solved
Recognise it
The signal
a^b mod p with b up to 1e18
1Brute force
Multiply n times.
2The observation
n multiplications: a^n = (a^(n/2))^2 * a^(n mod 2).
3Why it works
result * base^remaining equals the target throughout.
Reach for it when
- +modular inverse via Fermat a^(p-2)
- +repeated application of an associative operation
Not when
- ×modulus not prime when using Fermat inverses
Practice
0/9 solved
- Bit StringsCSESEasy
- Pow(x, n)Meta, GoogleMedium
- ExponentiationCSESMedium
- Exponentiation IICSESMedium
- Fibonacci NumbersCSESMedium
- Throwing DiceCSESMedium
- Graph Paths ICSESMedium
- Magic GemsCodeforces2100
- Product Oriented RecurrenceCodeforces2300
Pitfalls
Misconceptions
- !overflow in base*base before mod (use 128-bit or mulmod)