The naïve solution to the famous Fibonacci problem is exponential and most people can solve it in constant time. But can we do better? Definitely.
This is a classic problem in which the nth term is the sum of the previous two terms. The first two terms are 1 and 1. The third is 2, the fourth is 3, then 5, 8, etc.
Most commonly, people tend to employ a simple recursive solution that calls the function on the previous two terms. Obviously, this is incredibly inefficient and runs in exponential time (each function call branches into two separate function calls of size n-1 or n-2).
// calculates nth term of fibonacci, 1 indexed
Procedure Fib_Naive(int n):
if(n < 3):
return 1;
end_if
return Fib_Naive(n-1) + Fib_Naive(n-2)
end_Fib_Naive
A better approach would be either to have a recursive function that can either memorize or keep a temporary variable holding the previous two terms.
Alternatively, we could just keep a temp variable and program this iteratively, which is preferable since recursion generally takes longer than iterative solutions (this is because calls being pushed onto the call stack require extra assembly code instructions).
#computer-science #mathematics #code #linear-algebra #data-science