Learn
Fast Exponentiation (Binary Exponentiation)
Binary Exponentiation, also known as exponentiation by squaring or fast power, computes in time instead of . You use the property that when is even.
If you compute naively, you need multiplications. For , this won't finish in time. You repeatedly halve the exponent to achieve logarithmic complexity.
text
function power(x, n, mod):
result = 1
x = x mod mod
while n > 0:
if n is odd:
result = (result * x) mod mod
x = (x * x) mod mod
n = n / 2 (integer division)
return result
Example trace: (odd): , , (even): , (odd): , , (odd): , done
Applications: You use binary exponentiation for modular arithmetic, matrix exponentiation, cryptography (RSA), and computing large Fibonacci numbers.
Time complexity: multiplications.
Space complexity: for iterative version.