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
power(x, 0) = 1. That includes 00.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
The whole tree is drawn when the page opens. Next and Play start again from the first call.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(log n) | The exponent is halved on every call. |
| Stack | O(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