Fibonacci: The cost of redundancy
What you'll learn: Why simple recursion can be incredibly slow due to solving the same problem thousands of times.
The Tree of Waste
When we learn recursion, the Fibonacci sequence is the classic example. The rule is simple: each number is the sum of the two preceding ones (). However, when we translate this directly into code, we create a "Recursion Tree" that grows out of control.
Imagine you are building a brick wall. To place the 5th brick, you ask for the 4th and 3rd bricks. But to get the 4th brick, you ask for the 3rd and 2nd. Notice the problem? You are asking for the 3rd brick twice. As the numbers get higher, this redundancy explodes. By the time you calculate the 40th Fibonacci number, your computer is performing billions of redundant calculations, recalculating the same small values over and over again.
The Naive Code
Here is how that looks in C. It looks elegant, but it is hiding a massive performance cost:
#include <stdio.h>
int fibonacci(int n) {
// Base cases
if (n <= 1) {
return n;
}
// The Redundant Step:
// This calls itself twice, creating a massive branching tree.
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n = 40;
printf("Fibonacci of %d is %d\n", n, fibonacci(n));
return 0;
}
Why it crawls
In the code above, fibonacci(40) calls fibonacci(39) and fibonacci(38). But fibonacci(39) also calls fibonacci(38).
Every single step down the chain doubles the work. This is called exponential time complexity. If calculating takes one second, might take several minutes, and would take longer than the current age of the universe. The computer isn't stuck in an infinite loop; it’s just busy re-solving problems it already solved a millisecond ago.
In advanced recursion, we must learn to recognize these "overlapping subproblems." If your recursion tree looks like a bush where branches keep tangling back into the same spots, your code is doing too much redundant work.
Key takeaway
Naive recursion is often inefficient because it lacks a "memory," forcing the CPU to recalculate the same results repeatedly.