basics · beginner · ~15 min
Recursive base + smaller subproblem with O(log n) depth.
Raise an integer to a non-negative power using recursion and the binary-exponentiation (square-and-halve) trick.
Implement long ipow(int base, int exp) recursively, where exp >= 0. Use the identity:
ipow(b, e) = 1 when e == 0; ipow(b*b, e/2) when e is even; b * ipow(b, e-1) when e is odd. This keeps the recursion depth at O(log exp).
An int base and a non-negative int exp.
Returns base^exp as a long.
ipow(2, 10) -> 1024
ipow(3, 0) -> 1
ipow(5, 3) -> 125
ipow(10, 6) -> 1000000
exp == 0 returns 1 for any base (including base 0, by convention).A clean recursive function is the entry point to dynamic programming. Doing power as iterate-vs-recurse is the cleanest example.
An int base and a non-negative int exp.
base raised to exp, as a long.
Must be recursive. exp is non-negative; base^0 == 1.
long ipow(int base, int exp) { /* TODO */ return 0; }
Stack overflow at large exp if you do the naïve linear recursion.
exp == 0 → 1. base == 0, exp == 0 → 1 (convention).
O(log exp).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.