Nth Fibonacci Number (Recursive Solution, Dynamic Programming, Iterative Solution
Description:
In this article we shall use various methods for finding Nth Fibonacci Number.
Example:
Input: 9
The first line of input is Nth term.
Output:
34
The output consist of Nth Fibonacci number.
Method 1: (Recursive Solution)
Consider the example of finding Nth term of Fibonacci series. Below is the Fibonacci series: 1, 1, 2, 3, 5, 8, 13, 21 The first two terms of both 1, and each subsequent term is sum of previous two terms. Recursive definition of Fibonacci number is Fibonacci ( 1 ) = Fibonacci ( 2 ) = 1 if n = 1, 2 Fibonacci ( n ) = Fibonacci ( n - 1 ) + Fibonacci ( n - 2 ) for n > 2 The simplest recursive algorithm to compute Nth term of Fibonacci is direct translation of mathematical definition:
Complexity: Time Complexity: The above program will take O(2n) because of equation T(n) = T(n-1) + T(n-2) which is exponential.
Space Complexity: The space complexity for the above program is O(n) because of implementation of recursion on stack.
Method 2: (Dynamic Programming)
In our recursive method when we compute 20th term of Fibonacci then fib(3) is called 2584 times and fib(10) is called 89 times. It means that we are computing the 10th term of Fibonacci 89 times from scratch. In the ideal world, if we have already computed value of fib(10) once, we should not be recomputing it again. Memoization, Dynamix Programming are techniques used to solve this problem more efficiently. This can be achieved by storing the computed values in an array, and using them later when called.
longlongfib(int n, vector<longlong> &dp) { if(n == 1 || n == 2) return1; if(dp[n] != 0) // Checking if Nth term is already computed or not return dp[n]; return dp[n] = fib(n-1, dp)+fib(n-2, dp); // Storing the computed values }
intmain() { int n; cin >> n; vector<longlong> dp(101); // Creating the array for storing computed values cout << fib(n, dp); }
Complexity: Time Complexity: The above program will take O(n) time.
Space Complexity: The space complexity for the above program is O(n) for storing computed values.
Method 3: (Iterative Solution)
This method is pretty straightforward, we shall iteratively compute each value sequentially and store the previous two numbers only, because previous two numbers will get us the next Fibonacci number in series.
Program:
#include<iostream> usingnamespacestd;
longlongfib(int n) { longlong a = 1, b = 1, c; if(n == 1 || n == 2) return1;
for(int i = 3; i < n; i++) { c = a + b; a = b; b = c; } return c; }
intmain() { int n; cin >> n; cout << fib(n); }
Complexity: Time Complexity: The above program will take O(n) time.
Space Complexity: The space complexity for the above program is O(1) because we are storing only previous two terms.
Please write on comment section if you find any mistake or for any suggestions.
Comments