To solve a problem recursively: (1) find the smallest case you can answer directly, (2) express the problem in terms of a smaller instance of itself, (3) combine the result. Fast exponentiation shows the power of this: x^n = (x^(n/2))^2 (times x if n is odd) needs only about log n calls instead of n multiplications.
Remember
power(x, 0) = 1
power(x, n) = power(x, n / 2)^2 if n is even
power(x, n) = power(x, n / 2)^2 * x if n is odd
Reference
Cheat Sheet
Keep these facts handy while you work with Recursive Problem Solving in C in C.
#include <stdio.h>
static int calls;
static long long power(long long b, int e) {
calls++;
if (e == 0) return 1;
long long h = power(b, e / 2);
return (e % 2) ? h * h * b : h * h;
}
int main(void) {
calls = 0;
long long r = power(2, 10);
printf("2^10 = %lld (%d calls)\n", r, calls);
calls = 0;
r = power(3, 5);
printf("3^5 = %lld (%d calls)\n", r, calls);
return 0;
}
Output
2^10 = 1024 (5 calls)
3^5 = 243 (4 calls)
How It Works
For exponent 10 the calls use exponents 10, 5, 2, 1, and 0.
For exponent 5 they use 5, 2, 1, and 0.
The number of calls grows with log n, not n.
Edge Cases & Pitfalls
Check these before relying on Recursive Problem Solving in C in real programs.
overflow
Integer overflow
Large powers overflow quickly. Use a wider type or modular arithmetic.
neg
Negative exponents
This version assumes e >= 0.
Remember
Key Takeaways
Smallest case, smaller instance, combine.
Halving gives logarithmic depth.
Count calls to understand cost.
One line: To solve a problem recursively: (1) find the smallest case you can answer directly, (2) express the problem in terms of a smaller instance of itself, (3) combine the result.
Frequently Asked Questions
Define the simplest case, then assume your function already solves smaller inputs and use it to solve the current one.
It halves the exponent each call, so only about log2(n) multiplications are needed.
Continue with "Base Case and Recursive Case in C" next. See how calls descend to the base case and unwind back up. The C Recursion and Backtracking hub lists every topic in order.