Power / exponentiation (recursion)
Easy TimeO(n) SpaceO(n)
Raising a number to a power means multiplying it by itself that many times, so 2 to the power 5 is 32. Given a base and a whole-number exp, zero or greater, return the base raised to that power — without using ** or Math.pow. Any base to the power 0 is 1.
Examples
Example 1
- Input
- base = 2exp = 5
- Output
322 × 2 × 2 × 2 × 2 = 32.
Example 2
- Input
- base = 7exp = 0
- Output
- No multipliers at all, which leaves
11whatever the base was.
The Code
function power(base, exp) {
if (exp === 0) return 1;
return base * power(base, exp - 1);
}
power(2, 5);Done
More like this
All recursion examples (13) →- Fibonacci The classic branching recursion — every call spawns two more.
- Factorial The simplest linear recursion — one call, one multiply.
- Tower of Hanoi Move a stack of disks by trusting the recursion for the rest.
- GCD (Euclid) Euclid’s algorithm — recursion that shrinks fast.
- Sum of digits Peel one digit off at a time with the modulo trick.
- Mutual recursion Two functions that call each other all the way down.