Recursion · Divide and conquer · Exponent

Power Visualizer

What is Power

Return x raised to the power n. Treat 00 as 1.

Example. power(2, 5) returns 32. The calls are pow(2,5), pow(2,2), pow(2,1), then pow(2,0) = 1.

Input:  2 5
Output: 32

Constraints. 0 ≤ x ≤ 15 and 0 ≤ n ≤ 40. This picture caps n at 16 so the chain stays short.

Approach

Base case power(x, 0) = 1. That includes 00.
Recursive case Let half = power(x, n // 2). An even n returns half * half. An odd n returns half * half * x.

Halving the exponent makes a chain of length O(log n). A loop that multiplies x, n times, is a different recursion and a longer chain.

Recursion tree

Interactive recursion tree
Step 0/0 Answer —

The whole tree is drawn when the page opens. Next and Play start again from the first call.

def power(x, n):
if n == 0:
return 1
half = power(x, n // 2)
if n % 2 == 1:
return half * half * x
return half * half

Complexity

PieceCostWhy
TimeO(log n)The exponent is halved on every call.
StackO(log n)One pending call per halving.

Implementation

def power(x, n):
    if n == 0:
        return 1
    half = power(x, n // 2)
    if n % 2 == 1:
        return half * half * x
    return half * half