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
32
2 × 2 × 2 × 2 × 2 = 32.

Example 2

Input
base = 7exp = 0
Output
1
No multipliers at all, which leaves 1 whatever the base was.

The Code

function power(base, exp) {
  if (exp === 0) return 1;
  return base * power(base, exp - 1);
}
power(2, 5);
Done
Step through power(2, 5) call by call