Algorithms · Visualized
Fast Power
Divide & Conquer
Break a problem into independent subproblems, solve each, and combine the answers.
Computes x raised to the power n by recursively halving the exponent: x^n = (x^(n/2))², cutting the number of multiplications from O(n) down to O(log n). Time: O(log n) average, O(log n) worst; space: O(log n) — recursion depth.
Big-O: Classic D&C recursions: Merge Sort, Quick Sort, Maximum Subarray, Fast Power.
Fast Power (Divide & Conquer)
Divide & ConquerComputes x raised to the power n by recursively halving the exponent: x^n = (x^(n/2))², cutting the number of multiplications from O(n) down to O(log n). This is the same idea as Pow(x, n) but framed explicitly as divide and conquer.
How Fast Power Works
- Base case: if n equals 0, return 1.
- Recursively compute half = power(x, n / 2), dividing the exponent problem in half.
- Combine: square 'half' to get the result for an even exponent.
- If n was odd, multiply in one extra factor of x to account for the leftover.
- Return the combined result up through the recursive calls.
Fast Power Worked Example
Input: {x: 3, n: 6}
power(3,6): half=power(3,3). power(3,3): half=power(3,1)=3 (odd, ×3 extra) → power(3,1): half=power(3,0)=1 → 1×1×3=3. So power(3,3)=3×3×3=27. power(3,6)=27×27=729.
| n | result | factor | odd? |
|---|
def fast_power(x, n):
if n == 0:
return 1
half = fast_power(x, n // 2)
return half * half * (x if n % 2 else 1)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Fast Power Time & Space Complexity
When to Use Fast Power
- Cryptography (fast modular exponentiation), large number computation, and matrix exponentiation for fast Fibonacci computation.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.