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 & Conquer

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). This is the same idea as Pow(x, n) but framed explicitly as divide and conquer.

How Fast Power Works

  1. Base case: if n equals 0, return 1.
  2. Recursively compute half = power(x, n / 2), dividing the exponent problem in half.
  3. Combine: square 'half' to get the result for an even exponent.
  4. If n was odd, multiply in one extra factor of x to account for the leftover.
  5. 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.

Fast PowerO(log n)
Square the base and halve the exponent: xⁿ in O(log n) multiplications.
nresultfactorodd?
base3
exp6
Step 1 / 5
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Fast Power: compute 3^6 by squaring the factor and halving the exponent.
Python · Divide & Conquer in Code
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

BestO(log n)
AverageO(log n)
WorstO(log n)
SpaceO(log n) — recursion depth

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.