basics · beginner · ~15 min

Integer power by recursion

Recursive base + smaller subproblem with O(log n) depth.

Challenge

Implement long ipow(int base, int exp) recursively. exp >= 0. Use the binary-exponentiation trick: ipow(b, e) = (e is even ? ipow(b*b, e/2) : b * ipow(b, e-1)).

Why this matters

A clean recursive function is the entry point to dynamic programming. Doing power as iterate-vs-recurse is the cleanest example.

Input format

base and non-negative exp.

Output format

base^exp as long.

Constraints

Must be recursive.

Starter code

long ipow(int base, int exp) { /* TODO */ return 0; }

Common mistakes

Stack overflow at large exp if you do the naïve linear recursion.

Edge cases to handle

exp == 0 → 1. base == 0, exp == 0 → 1 (convention).

Complexity

O(log exp).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.