Fast Exponentiation Algorithm Using Divide and Conquer
Fast exponentiation (also known as exponentiation by squaring) is an efficient algorithm to compute ( x^n ) (where ( x ) is the base and ( n ) is the non-negative integer exponent) in ( O(\log n) ) time, compared to the naive ( O(n) ) method of repeated multiplication.
This leverages the divide and conquer paradigm:
- Divide: Recursively compute ( x^{n/2} ) (halving the exponent each time).
- Conquer: Use the identity ( x^n = (x^{n/2})^2 ) if ( n ) is even, or ( x^n = x \cdot (x^{(n-1)/2})^2 ) if ( n ) is odd.
- Combine: Square the result from the subproblem(s) and multiply by ( x ) if needed.
The recursion tree has depth ( O(\log n) ), making it highly efficient.
Recursive Pseudocode
function power(x, n):
if n == 0:
return 1
if n == 1:
return x
half = power(x, n // 2) // Divide: recurse on half exponent
result = half * half // Conquer: square the half result
if n % 2 == 1: // Handle odd case
result = x * result
return result
Example Trace: Compute ( 3^5 )
power(3, 5): n=5 (odd) → half=power(3,2) → result=3 * (half*half)
power(3,2): n=2 (even) → half=power(3,1) → result=half*half
- half=3 → result=3*3=9
- Back to n=5: half=9 → result=99=81 → 381=243
Correct: ( 3^5 = 243 ).
Python Implementation (Recursive)
def power(x, n):
if n == 0:
return 1
if n == 1:
return x
half = power(x, n // 2)
result = half * half
if n % 2 == 1:
result = x * result
return result
# Test
print(power(3, 5)) # Output: 243
print(power(2, 10)) # Output: 1024
Iterative Version (for better space efficiency, O(1) space)
While the recursive version embodies divide-and-conquer clearly, an iterative version simulates the recursion using a loop:
def power_iterative(x, n):
result = 1
while n > 0:
if n % 2 == 1:
result *= x
x *= x # Square the base
n //= 2
return result
Complexity Analysis
- Time: ( O(\log n) ) – Each recursion level halves ( n ), and we do ~2 operations per level.
- Space (recursive): ( O(\log n) ) recursion depth.
- Space (iterative): ( O(1) ).
- Handles large ( n ) well (e.g., ( 2^{1000000} )) if using big integers (Python supports natively).
Edge Cases Handled
- ( n = 0 ): Returns 1 (( x^0 = 1 )).
- ( n = 1 ): Returns ( x ).
- Negative ( n ): Extend with ( 1 / power(x, -n) ) if needed (not included here).
- ( x = 0 ): Returns 0 for ( n > 0 ), 1 for ( n = 0 ).
This algorithm is widely used in cryptography (e.g., modular exponentiation for RSA) and libraries like Python's pow(x, n). For modular arithmetic, add result %= mod in multiplications.