The simplest way to find the time complexity of the Fibonacci sequence is to look at the recursive approach:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
Here's how to analyze it:
-
Recursive Calls: The function fibonacci(n) calls fibonacci(n-1) and fibonacci(n-2). This branching creates a tree of calls.
-
Nodes in the Tree: The number of nodes in this tree grows roughly exponentially. You can think of each level of the tree roughly doubling in size as n increases.
-
Estimate: A good estimate is that the time complexity is approximately O(2n). While not perfectly accurate due to overlapping subproblems, it highlights the exponential growth. A more precise analysis can show it's closer to O(((1+sqrt(5))/2)n), where (1+sqrt(5))/2 is the golden ratio.
-
Why Exponential? Because calculating fibonacci(n) involves recalculating the values of smaller Fibonacci numbers multiple times. For example, calculating fibonacci(5) involves calculating fibonacci(3) multiple times. This redundant computation leads to the explosion in execution time.
Therefore, the simplest answer for the time complexity of the naive recursive Fibonacci implementation is O(2n).
Key Takeaway: While simple to write, the recursive Fibonacci function is extremely inefficient for larger values of n due to its exponential time complexity.
Why Not Something Else?
- O(n): This would imply a linear relationship between input
n and execution time. The recursive calls quickly make it much worse than linear.
- O(log n): Logarithmic complexity is generally associated with algorithms that divide the problem space in half at each step. The Fibonacci recursion does not do this.
- O(n2): Quadratic complexity is better than exponential, but the recursion grows much faster than that.
The O(2n) estimate is straightforward to grasp by visualizing the call tree of the recursive function and recognizing the approximately doubling of calls with each increment of n.