Pow(x, n)
Implement pow(x, n), which calculates x raised to the power n (x ⁿ ). Use recursion with the fast-power trick: halve n each call instead of multiplying x by itself n times. The base case is n = 0, which returns 1. Otherwise recurse once on half of n, then square that result — if n is odd, multiply in one more x. If n is negative, compute pow(x, -n) and invert it.
Constraints
- -100.0 < x < 100.0
- -231 ≤ n ≤ 231 - 1
- n is an integer
Example
x = 2.0, n = 101024.0Explanation 2¹⁰ = 1024.
In plain terms
- Divide and conquer
- Breaking a problem into a smaller version of itself, solving that smaller piece once, then combining its result to build the original answer — here, computing one half-power and squaring it instead of repeating the work twice.
Halve the exponent each call, square on the way back up
n = 10 is even. Call pow(2, 5) and wait to square its result.
What happens in this step
helper(2, 10) calls helper(2, 5) 10 is even, so half = helper(2, floor(10/2)) = helper(2, 5). The result will just be half * half once that returns.
Steps to visualize
- If n is negative, compute pow(x, -n) and invert the result at the end.
- Base case: n = 0 returns 1 — any number to the power 0 is 1.
- If n is even, recurse once on pow(x, n / 2) and square the result.
- If n is odd, recurse on pow(x, (n - 1) / 2), square it, and multiply by one more x.
- Each call waits on the stack for its single recursive call before it can square (and possibly multiply) the answer.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
n = 10 is even. Call pow(2, 5) and wait to square its result.
What happens in this step
helper(2, 10) calls helper(2, 5) 10 is even, so half = helper(2, floor(10/2)) = helper(2, 5). The result will just be half * half once that returns.
Solution
function myPow(x, n) {
function helper(base, exp) {
if (exp === 0) {
return 1; // base case
}
const half = helper(base, Math.floor(exp / 2)); // recursive case
if (exp % 2 === 0) {
return half * half;
}
return half * half * base;
}
if (n < 0) {
return 1 / helper(x, -n);
}
return helper(x, n);
}- Time
- O(log n)
- Space
- O(log n)
Test cases
| Input | Expected | Covers |
|---|---|---|
x = 2.0, n = 10 | 1024.0 | example from the docstring |
x = 2.0, n = -2 | 0.25 | negative exponent inverts the result |
x = 2.0, n = 0 | 1.0 | base case, any base to the power 0 is 1 |
x = 2.0, n = 1 | 2.0 | one recursive call deep, odd exponent |
x = -2.0, n = 3 | -8.0 | negative base with an odd exponent stays negative |
x = 0.5, n = 2 | 0.25 | fractional base |
x = 2.0, n = 20 | 1048576.0 | a deeper recursion, several halvings |
x = 1.0, n = 2147483647 | 1.0 | base 1 at the upper bound of n, stays shallow thanks to halving |