Given a positive integer n, the task is to find the nth Fibonacci number.
The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
Example:
Input: n = 2
Output: 1
Explanation: 1 is the 2nd number of Fibonacci series.
Input: n = 5
Output: 5
Explanation: 5 is the 5th number of Fibonacci series.
[Naive Approach] Using Recursion
We can use recursion to solve this problem because any Fibonacci number n depends on previous two Fibonacci numbers. Therefore, this approach repeatedly breaks down the problem until it reaches the base cases.
Recurrence relation:
- Base case: F(n) = n, when n = 0 or n = 1
- Recursive case: F(n) = F(n-1) + F(n-2) for n>1
C++ #include <bits/stdc++.h> using namespace std; // Function to calculate the nth Fibonacci number using recursion int nthFibonacci(int n){ // Base case: if n is 0 or 1, return n if (n <= 1){ return n; } // Recursive case: sum of the two preceding Fibonacci numbers return nthFibonacci(n - 1) + nthFibonacci(n - 2); } int main(){ int n = 5; int result = nthFibonacci(n); cout << result << endl; return 0; }
C #include <stdio.h> // Function to calculate the nth Fibonacci number using recursion int nthFibonacci(int n){ // Base case: if n is 0 or 1, return n if (n <= 1){ return n; } // Recursive case: sum of the two preceding Fibonacci numbers return nthFibonacci(n - 1) + nthFibonacci(n - 2); } int main(){ int n = 5; int result = nthFibonacci(n); printf("%d\n", result); return 0; }
Java class GfG { // Function to calculate the nth Fibonacci number using // recursion static int nthFibonacci(int n){ // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Recursive case: sum of the two preceding // Fibonacci numbers return nthFibonacci(n - 1) + nthFibonacci(n - 2); } public static void main(String[] args){ int n = 5; int result = nthFibonacci(n); System.out.println(result); } }
Python def nth_fibonacci(n): # Base case: if n is 0 or 1, return n if n <= 1: return n # Recursive case: sum of the two preceding Fibonacci numbers return nth_fibonacci(n - 1) + nth_fibonacci(n - 2) n = 5 result = nth_fibonacci(n) print(result)
C# using System; class GfG { // Function to calculate the nth Fibonacci number using // recursion static int nthFibonacci(int n){ // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Recursive case: sum of the two preceding // Fibonacci numbers return nthFibonacci(n - 1) + nthFibonacci(n - 2); } static void Main(){ int n = 5; int result = nthFibonacci(n); Console.WriteLine(result); } }
JavaScript function nthFibonacci(n){ // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Recursive case: sum of the two preceding Fibonacci // numbers return nthFibonacci(n - 1) + nthFibonacci(n - 2); } let n = 5; let result = nthFibonacci(n); console.log(result);
Time Complexity: O(2n)
Auxiliary Space: O(n), due to recursion stack
[Expected Approach-1] Memoization Approach
In the previous approach there is a lot of redundant calculation that are calculating again and again, So we can store the results of previously computed Fibonacci numbers in a memo table to avoid redundant calculations. This will make sure that each Fibonacci number is only computed once, this will reduce the exponential time complexity of the naive approach O(2^n) into a more efficient O(n) time complexity.
C++ #include <bits/stdc++.h> using namespace std; // Function to calculate the nth Fibonacci number using memoization int nthFibonacciUtil(int n, vector<int>& memo) { // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Check if the result is already in the memo table if (memo[n] != -1) { return memo[n]; } // Recursive case: calculate Fibonacci number // and store it in memo memo[n] = nthFibonacciUtil(n - 1, memo) + nthFibonacciUtil(n - 2, memo); return memo[n]; } // Wrapper function that handles both initialization // and Fibonacci calculation int nthFibonacci(int n) { // Create a memoization table and initialize with -1 vector<int> memo(n + 1, -1); // Call the utility function return nthFibonacciUtil(n, memo); } int main() { int n = 5; int result = nthFibonacci(n); cout << result << endl; return 0; }
C #include <stdio.h> // Function to calculate the nth Fibonacci number using memoization int nthFibonacciUtil(int n, int memo[]) { // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Check if the result is already in the memo table if (memo[n] != -1) { return memo[n]; } // Recursive case: calculate Fibonacci number // and store it in memo memo[n] = nthFibonacciUtil(n - 1, memo) + nthFibonacciUtil(n - 2, memo); return memo[n]; } // Wrapper function that handles both initialization // and Fibonacci calculation int nthFibonacci(int n) { // Create a memoization table and initialize with -1 int memo[n + 1]; for (int i = 0; i <= n; i++) { memo[i] = -1; } // Call the utility function return nthFibonacciUtil(n, memo); } int main() { int n = 5; int result = nthFibonacci(n); printf("%d\n", result); return 0; }
Java import java.util.Arrays; class GfG { // Function to calculate the nth Fibonacci number using memoization static int nthFibonacciUtil(int n, int[] memo) { // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Check if the result is already in the memo table if (memo[n] != -1) { return memo[n]; } // Recursive case: calculate Fibonacci number // and store it in memo memo[n] = nthFibonacciUtil(n - 1, memo) + nthFibonacciUtil(n - 2, memo); return memo[n]; } // Wrapper function that handles both initialization // and Fibonacci calculation static int nthFibonacci(int n) { // Create a memoization table and initialize with -1 int[] memo = new int[n + 1]; Arrays.fill(memo, -1); // Call the utility function return nthFibonacciUtil(n, memo); } public static void main(String[] args) { int n = 5; int result = nthFibonacci(n); System.out.println(result); } }
Python # Function to calculate the nth Fibonacci number using memoization def nth_fibonacci_util(n, memo): # Base case: if n is 0 or 1, return n if n <= 1: return n # Check if the result is already in the memo table if memo[n] != -1: return memo[n] # Recursive case: calculate Fibonacci number # and store it in memo memo[n] = nth_fibonacci_util(n - 1, memo) + nth_fibonacci_util(n - 2, memo) return memo[n] # Wrapper function that handles both initialization # and Fibonacci calculation def nth_fibonacci(n): # Create a memoization table and initialize with -1 memo = [-1] * (n + 1) # Call the utility function return nth_fibonacci_util(n, memo) if __name__ == "__main__": n = 5 result = nth_fibonacci(n) print(result)
C# using System; class GfG { // Function to calculate the nth Fibonacci number using memoization static int nthFibonacciUtil(int n, int[] memo) { // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Check if the result is already in the memo table if (memo[n] != -1) { return memo[n]; } // Recursive case: calculate Fibonacci number // and store it in memo memo[n] = nthFibonacciUtil(n - 1, memo) + nthFibonacciUtil(n - 2, memo); return memo[n]; } // Wrapper function that handles both initialization // and Fibonacci calculation static int nthFibonacci(int n) { // Create a memoization table and initialize with -1 int[] memo = new int[n + 1]; Array.Fill(memo, -1); // Call the utility function return nthFibonacciUtil(n, memo); } public static void Main(string[] args) { int n = 5; int result = nthFibonacci(n); Console.WriteLine(result); } }
JavaScript // Function to calculate the nth Fibonacci number using memoization function nthFibonacciUtil(n, memo) { // Base case: if n is 0 or 1, return n if (n <= 1) { return n; } // Check if the result is already in the memo table if (memo[n] !== -1) { return memo[n]; } // Recursive case: calculate Fibonacci number // and store it in memo memo[n] = nthFibonacciUtil(n - 1, memo) + nthFibonacciUtil(n - 2, memo); return memo[n]; } // Wrapper function that handles both initialization // and Fibonacci calculation function nthFibonacci(n) { // Create a memoization table and initialize with -1 let memo = new Array(n + 1).fill(-1); // Call the utility function return nthFibonacciUtil(n, memo); } let n = 5; let result = nthFibonacci(n); console.log(result);
Time Complexity: O(n), each fibonacci number is calculated only one times from 1 to n;
Auxiliary Space: O(n), due to memo table
[Expected Approach-2] Bottom-Up Approach
This approach uses dynamic programming to solve the Fibonacci problem by storing previously calculated Fibonacci numbers, avoiding the repeated calculations of the recursive approach. Instead of breaking down the problem recursively, it iteratively builds up the solution by calculating Fibonacci numbers from the bottom up.
C++ #include <bits/stdc++.h> using namespace std; // Function to calculate the nth Fibonacci number using recursion int nthFibonacci(int n){ // Handle the edge cases if (n <= 1) return n; // Create a vector to store Fibonacci numbers vector<int> dp(n + 1); // Initialize the first two Fibonacci numbers dp[0] = 0; dp[1] = 1; // Fill the vector iteratively for (int i = 2; i <= n; ++i){ // Calculate the next Fibonacci number dp[i] = dp[i - 1] + dp[i - 2]; } // Return the nth Fibonacci number return dp[n]; } int main(){ int n = 5; int result = nthFibonacci(n); cout << result << endl; return 0; }
C #include <stdio.h> // Function to calculate the nth Fibonacci number // using iteration int nthFibonacci(int n) { // Handle the edge cases if (n <= 1) return n; // Create an array to store Fibonacci numbers int dp[n + 1]; // Initialize the first two Fibonacci numbers dp[0] = 0; dp[1] = 1; // Fill the array iteratively for (int i = 2; i <= n; ++i) { dp[i] = dp[i - 1] + dp[i - 2]; } // Return the nth Fibonacci number return dp[n]; } int main() { int n = 5; int result = nthFibonacci(n); printf("%d\n", result); return 0; }
Java class GfG { // Function to calculate the nth Fibonacci number using iteration static int nthFibonacci(int n) { // Handle the edge cases if (n <= 1) return n; // Create an array to store Fibonacci numbers int[] dp = new int[n + 1]; // Initialize the first two Fibonacci numbers dp[0] = 0; dp[1] = 1; // Fill the array iteratively for (int i = 2; i <= n; ++i) { dp[i] = dp[i - 1] + dp[i - 2]; } // Return the nth Fibonacci number return dp[n]; } public static void main(String[] args) { int n = 5; int result = nthFibonacci(n); System.out.println(result); } }
Python def nth_fibonacci(n): # Handle the edge cases if n <= 1: return n # Create a list to store Fibonacci numbers dp = [0] * (n + 1) # Initialize the first two Fibonacci numbers dp[0] = 0 dp[1] = 1 # Fill the list iteratively for i in range(2, n + 1): dp[i] = dp[i - 1] + dp[i - 2] # Return the nth Fibonacci number return dp[n] n = 5 result = nth_fibonacci(n) print(result)
C# using System; class GfG { // Function to calculate the nth Fibonacci number using iteration public static int nthFibonacci(int n) { // Handle the edge cases if (n <= 1) return n; // Create an array to store Fibonacci numbers int[] dp = new int[n + 1]; // Initialize the first two Fibonacci numbers dp[0] = 0; dp[1] = 1; // Fill the array iteratively for (int i = 2; i <= n; ++i) { dp[i] = dp[i - 1] + dp[i - 2]; } // Return the nth Fibonacci number return dp[n]; } static void Main() { int n = 5; int result = nthFibonacci(n); Console.WriteLine(result); } }
JavaScript function nthFibonacci(n) { // Handle the edge cases if (n <= 1) return n; // Create an array to store Fibonacci numbers let dp = new Array(n + 1); // Initialize the first two Fibonacci numbers dp[0] = 0; dp[1] = 1; // Fill the array iteratively for (let i = 2; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } // Return the nth Fibonacci number return dp[n]; } let n = 5; let result = nthFibonacci(n); console.log(result);
Time Complexity: O(n), the loop runs from 2 to n, performing a constant amount of work per iteration.
Auxiliary Space: O(n), due to the use of an extra array to store Fibonacci numbers up to n.
[Expected Approach-3] Space Optimized Approach
This approach is just an optimization of the above iterative approach, Instead of using the extra array for storing the Fibonacci numbers, we can store the values in the variables. We keep the previous two numbers only because that is all we need to get the next Fibonacci number in series.
C++ #include <bits/stdc++.h> using namespace std; // Function to calculate the nth Fibonacci number // using space optimization int nthFibonacci(int n){ if (n <= 1) return n; // To store the curr Fibonacci number int curr = 0; // To store the previous Fibonacci number int prev1 = 1; int prev2 = 0; // Loop to calculate Fibonacci numbers from 2 to n for (int i = 2; i <= n; i++){ // Calculate the curr Fibonacci number curr = prev1 + prev2; // Update prev2 to the last Fibonacci number prev2 = prev1; // Update prev1 to the curr Fibonacci number prev1 = curr; } return curr; } int main() { int n = 5; int result = nthFibonacci(n); cout << result << endl; return 0; }
C #include <stdio.h> // Function to calculate the nth Fibonacci number // using space optimization int nthFibonacci(int n) { if (n <= 1) return n; // To store the curr Fibonacci number int curr = 0; // To store the previous Fibonacci numbers int prev1 = 1; int prev2 = 0; // Loop to calculate Fibonacci numbers from 2 to n for (int i = 2; i <= n; i++) { // Calculate the curr Fibonacci number curr = prev1 + prev2; // Update prev2 to the last Fibonacci number prev2 = prev1; // Update prev1 to the curr Fibonacci number prev1 = curr; } return curr; } int main() { int n = 5; int result = nthFibonacci(n); printf("%d\n", result); return 0; }
Java class GfG { // Function to calculate the nth Fibonacci number // using space optimization static int nthFibonacci(int n) { if (n <= 1) return n; // To store the curr Fibonacci number int curr = 0; // To store the previous Fibonacci numbers int prev1 = 1; int prev2 = 0; // Loop to calculate Fibonacci numbers from 2 to n for (int i = 2; i <= n; i++) { // Calculate the curr Fibonacci number curr = prev1 + prev2; // Update prev2 to the last Fibonacci number prev2 = prev1; // Update prev1 to the curr Fibonacci number prev1 = curr; } return curr; } public static void main(String[] args) { int n = 5; int result = nthFibonacci(n); System.out.println(result); } }
Python def nth_fibonacci(n): if n <= 1: return n # To store the curr Fibonacci number curr = 0 # To store the previous Fibonacci numbers prev1 = 1 prev2 = 0 # Loop to calculate Fibonacci numbers from 2 to n for i in range(2, n + 1): # Calculate the curr Fibonacci number curr = prev1 + prev2 # Update prev2 to the last Fibonacci number prev2 = prev1 # Update prev1 to the curr Fibonacci number prev1 = curr return curr n = 5 result = nth_fibonacci(n) print(result)
C# using System; class GfG { // Function to calculate the nth Fibonacci number // using space optimization public static int nthFibonacci(int n) { if (n <= 1) return n; // To store the curr Fibonacci number int curr = 0; // To store the previous Fibonacci numbers int prev1 = 1; int prev2 = 0; // Loop to calculate Fibonacci numbers from 2 to n for (int i = 2; i <= n; i++) { // Calculate the curr Fibonacci number curr = prev1 + prev2; // Update prev2 to the last Fibonacci number prev2 = prev1; // Update prev1 to the curr Fibonacci number prev1 = curr; } return curr; } static void Main() { int n = 5; int result = nthFibonacci(n); Console.WriteLine(result); } }
JavaScript function nthFibonacci(n) { if (n <= 1) return n; // To store the curr Fibonacci number let curr = 0; // To store the previous Fibonacci numbers let prev1 = 1; let prev2 = 0; // Loop to calculate Fibonacci numbers from 2 to n for (let i = 2; i <= n; i++) { // Calculate the curr Fibonacci number curr = prev1 + prev2; // Update prev2 to the last Fibonacci number prev2 = prev1; // Update prev1 to the curr Fibonacci number prev1 = curr; } return curr; } let n = 5; let result = nthFibonacci(n); console.log(result);
Time Complexity: O(n), The loop runs from 2 to n, performing constant time operations in each iteration.)
Auxiliary Space: O(1), Only a constant amount of extra space is used to store the current and two previous Fibonacci numbers.
Using Matrix Exponentiation – O(log(n)) time and O(log(n)) space
We know that each Fibonacci number is the sum of previous two Fibonacci numbers. we would either add numbers repeatedly or use loops or recursion, which takes time. But with matrix exponentiation, we can calculate Fibonacci numbers much faster by working with matrices. There’s a special matrix (transformation matrix) that represents how Fibonacci numbers work. It looks like this: [Tex]\begin{pmatrix}1 & 1 \\1 & 0 \end{pmatrix}[/Tex]This matrix captures the Fibonacci relationship. If we multiply this matrix by itself multiple times, it can give us Fibonacci numbers.
To find the Nth Fibonacci number we need to multiple transformation matrix (n-1) times, the matrix equation for the Fibonacci sequence looks like:
[Tex]\begin{pmatrix}1 & 1 \\1 & 0\end{pmatrix}^{n-1}=\begin{pmatrix}F(n) & F(n-1) \\F(n-1) & F(n-2)\end{pmatrix}[/Tex]
After raising the transformation matrix to the power n – 1, the top-left element F(n) will gives the nth Fibonacci number.
C++ #include <bits/stdc++.h> using namespace std; // Function to multiply two 2x2 matrices void multiply(vector<vector<int>>& mat1, vector<vector<int>>& mat2) { // Perform matrix multiplication int x = mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0]; int y = mat1[0][0] * mat2[0][1] + mat1[0][1] * mat2[1][1]; int z = mat1[1][0] * mat2[0][0] + mat1[1][1] * mat2[1][0]; int w = mat1[1][0] * mat2[0][1] + mat1[1][1] * mat2[1][1]; // Update matrix mat1 with the result mat1[0][0] = x; mat1[0][1] = y; mat1[1][0] = z; mat1[1][1] = w; } // Function to perform matrix exponentiation void matrixPower(vector<vector<int>>& mat1, int n) { // Base case for recursion if (n == 0 || n == 1) return; // Initialize a helper matrix vector<vector<int>> mat2 = {{1, 1}, {1, 0}}; // Recursively calculate mat1^(n/2) matrixPower(mat1, n / 2); // Square the matrix mat1 multiply(mat1, mat1); // If n is odd, multiply by the helper matrix mat2 if (n % 2 != 0) { multiply(mat1, mat2); } } // Function to calculate the nth Fibonacci number // using matrix exponentiation int nthFibonacci(int n) { if (n <= 1) return n; // Initialize the transformation matrix vector<vector<int>> mat1 = {{1, 1}, {1, 0}}; // Raise the matrix mat1 to the power of (n - 1) matrixPower(mat1, n - 1); // The result is in the top-left cell of the matrix return mat1[0][0]; } int main() { int n = 5; int result = nthFibonacci(n); cout << result << endl; return 0; }
C #include <stdio.h> // Function to multiply two 2x2 matrices void multiply(int mat1[2][2], int mat2[2][2]) { // Perform matrix multiplication int x = mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0]; int y = mat1[0][0] * mat2[0][1] + mat1[0][1] * mat2[1][1]; int z = mat1[1][0] * mat2[0][0] + mat1[1][1] * mat2[1][0]; int w = mat1[1][0] * mat2[0][1] + mat1[1][1] * mat2[1][1]; // Update matrix mat1 with the result mat1[0][0] = x; mat1[0][1] = y; mat1[1][0] = z; mat1[1][1] = w; } // Function to perform matrix exponentiation void matrixPower(int mat1[2][2], int n) { // Base case for recursion if (n == 0 || n == 1) return; // Initialize a helper matrix int mat2[2][2] = {{1, 1}, {1, 0}}; // Recursively calculate mat1^(n/2) matrixPower(mat1, n / 2); // Square the matrix mat1 multiply(mat1, mat1); // If n is odd, multiply by the helper matrix mat2 if (n % 2 != 0) { multiply(mat1, mat2); } } // Function to calculate the nth Fibonacci number int nthFibonacci(int n) { if (n <= 1) return n; // Initialize the transformation matrix int mat1[2][2] = {{1, 1}, {1, 0}}; // Raise the matrix mat1 to the power of (n - 1) matrixPower(mat1, n - 1); // The result is in the top-left cell of the matrix return mat1[0][0]; } int main() { int n = 5; int result = nthFibonacci(n); printf("%d\n", result); return 0; }
Java import java.util.*; // Function to multiply two 2x2 matrices class GfG { static void multiply(int[][] mat1, int[][] mat2) { // Perform matrix multiplication int x = mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0]; int y = mat1[0][0] * mat2[0][1] + mat1[0][1] * mat2[1][1]; int z = mat1[1][0] * mat2[0][0] + mat1[1][1] * mat2[1][0]; int w = mat1[1][0] * mat2[0][1] + mat1[1][1] * mat2[1][1]; // Update matrix mat1 with the result mat1[0][0] = x; mat1[0][1] = y; mat1[1][0] = z; mat1[1][1] = w; } // Function to perform matrix exponentiation static void matrixPower(int[][] mat1, int n) { // Base case for recursion if (n == 0 || n == 1) return; // Initialize a helper matrix int[][] mat2 = {{1, 1}, {1, 0}}; // Recursively calculate mat1^(n/2) matrixPower(mat1, n / 2); // Square the matrix mat1 multiply(mat1, mat1); // If n is odd, multiply by the helper matrix mat2 if (n % 2 != 0) { multiply(mat1, mat2); } } // Function to calculate the nth Fibonacci number static int nthFibonacci(int n) { if (n <= 1) return n; // Initialize the transformation matrix int[][] mat1 = {{1, 1}, {1, 0}}; // Raise the matrix mat1 to the power of (n - 1) matrixPower(mat1, n - 1); // The result is in the top-left cell of the matrix return mat1[0][0]; } public static void main(String[] args) { int n = 5; int result = nthFibonacci(n); System.out.println(result); } }
Python # Function to multiply two 2x2 matrices def multiply(mat1, mat2): # Perform matrix multiplication x = mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0] y = mat1[0][0] * mat2[0][1] + mat1[0][1] * mat2[1][1] z = mat1[1][0] * mat2[0][0] + mat1[1][1] * mat2[1][0] w = mat1[1][0] * mat2[0][1] + mat1[1][1] * mat2[1][1] # Update matrix mat1 with the result mat1[0][0], mat1[0][1] = x, y mat1[1][0], mat1[1][1] = z, w # Function to perform matrix exponentiation def matrix_power(mat1, n): # Base case for recursion if n == 0 or n == 1: return # Initialize a helper matrix mat2 = [[1, 1], [1, 0]] # Recursively calculate mat1^(n // 2) matrix_power(mat1, n // 2) # Square the matrix mat1 multiply(mat1, mat1) # If n is odd, multiply by the helper matrix mat2 if n % 2 != 0: multiply(mat1, mat2) # Function to calculate the nth Fibonacci number def nth_fibonacci(n): if n <= 1: return n # Initialize the transformation matrix mat1 = [[1, 1], [1, 0]] # Raise the matrix mat1 to the power of (n - 1) matrix_power(mat1, n - 1) # The result is in the top-left cell of the matrix return mat1[0][0] if __name__ == "__main__": n = 5 result = nth_fibonacci(n) print(result)
C# using System; class GfG { // Function to multiply two 2x2 matrices static void Multiply(int[,] mat1, int[,] mat2) { // Perform matrix multiplication int x = mat1[0,0] * mat2[0,0] + mat1[0,1] * mat2[1,0]; int y = mat1[0,0] * mat2[0,1] + mat1[0,1] * mat2[1,1]; int z = mat1[1,0] * mat2[0,0] + mat1[1,1] * mat2[1,0]; int w = mat1[1,0] * mat2[0,1] + mat1[1,1] * mat2[1,1]; // Update matrix mat1 with the result mat1[0,0] = x; mat1[0,1] = y; mat1[1,0] = z; mat1[1,1] = w; } // Function to perform matrix exponentiation static void MatrixPower(int[,] mat1, int n) { // Base case for recursion if (n == 0 || n == 1) return; // Initialize a helper matrix int[,] mat2 = { {1, 1}, {1, 0} }; // Recursively calculate mat1^(n / 2) MatrixPower(mat1, n / 2); // Square the matrix mat1 Multiply(mat1, mat1); // If n is odd, multiply by the helper matrix mat2 if (n % 2 != 0) { Multiply(mat1, mat2); } } // Function to calculate the nth Fibonacci number static int NthFibonacci(int n) { if (n <= 1) return n; // Initialize the transformation matrix int[,] mat1 = { {1, 1}, {1, 0} }; // Raise the matrix mat1 to the power of (n - 1) MatrixPower(mat1, n - 1); // The result is in the top-left cell of the matrix return mat1[0,0]; } public static void Main(string[] args) { int n = 5; int result = NthFibonacci(n); Console.WriteLine(result); } }
JavaScript // Function to multiply two 2x2 matrices function multiply(mat1, mat2) { // Perform matrix multiplication const x = mat1[0][0] * mat2[0][0] + mat1[0][1] * mat2[1][0]; const y = mat1[0][0] * mat2[0][1] + mat1[0][1] * mat2[1][1]; const z = mat1[1][0] * mat2[0][0] + mat1[1][1] * mat2[1][0]; const w = mat1[1][0] * mat2[0][1] + mat1[1][1] * mat2[1][1]; // Update matrix mat1 with the result mat1[0][0] = x; mat1[0][1] = y; mat1[1][0] = z; mat1[1][1] = w; } // Function to perform matrix exponentiation function matrixPower(mat1, n) { // Base case for recursion if (n === 0 || n === 1) return; // Initialize a helper matrix const mat2 = [[1, 1], [1, 0]]; // Recursively calculate mat1^(n // 2) matrixPower(mat1, Math.floor(n / 2)); // Square the matrix mat1 multiply(mat1, mat1); // If n is odd, multiply by the helper matrix mat2 if (n % 2 !== 0) { multiply(mat1, mat2); } } // Function to calculate the nth Fibonacci number function nthFibonacci(n) { if (n <= 1) return n; // Initialize the transformation matrix const mat1 = [[1, 1], [1, 0]]; // Raise the matrix mat1 to the power of (n - 1) matrixPower(mat1, n - 1); // The result is in the top-left cell of the matrix return mat1[0][0]; } const n = 5; const result = nthFibonacci(n); console.log(result);
Time Complexity: O(log(n), We have used exponentiation by squaring, which reduces the number of matrix multiplications to O(log n), because with each recursive call, the power is halved.
Auxiliary Space: O(log n), due to the recursion stack.
[Other Approach] Using Golden ratio
The nth Fibonacci number can be found using the Golden Ratio, which is approximately = [Tex]\phi = \frac{1 + \sqrt{5}}{2}[/Tex]. The intuition behind this method is based on Binet’s formula, which expresses the nth Fibonacci number directly in terms of the Golden Ratio.
Binet’s Formula: The nth Fibonacci number F(n) can be calculated using the formula: [Tex]F(n) = \frac{\phi^n – (1 – \phi)^n}{\sqrt{5}}[/Tex]
For more detail for this approach, please refer to our article “Find nth Fibonacci number using Golden ratio“
Related Articles:
Similar Reads
How to check if a given number is Fibonacci number?
Given a number ânâ, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples :Input : 8Output : YesInput : 34Output : YesInput : 41Output : NoApproach 1:A simple way is to generate Fibonacci numbers until the generated number
15+ min read
Nth Fibonacci Number
Given a positive integer n, the task is to find the nth Fibonacci number. The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21 Example: Inp
15+ min read
C++ Program For Fibonacci Numbers
The Fibonacci series is the sequence where each number is the sum of the previous two numbers. The first two numbers of the Fibonacci series are 0 and 1 and are used to generate the whole series. In this article, we will learn how to find the nth Fibonacci number in C++. Examples Input: 5Output: 5Ex
5 min read
Python Program for n-th Fibonacci number
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2With seed values F0 = 0 and F1 = 1.Table of Content Python Program for n-th Fibonacci number Using Formula Python Program for n-th Fibonacci number Using RecursionPython Program for n-th
6 min read
Interesting Programming facts about Fibonacci numbers
We know Fibonacci number, Fn = Fn-1 + Fn-2. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, .... . Here are some interesting facts about Fibonacci number : 1. Pattern in Last digits of Fibonacci numbers : Last digits of first few Fibonacci Numbers ar
15+ min read
Find nth Fibonacci number using Golden ratio
Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: [Tex]\varphi
6 min read
Fast Doubling method to find the Nth Fibonacci number
Given an integer N, the task is to find the N-th Fibonacci numbers.Examples: Input: N = 3 Output: 2 Explanation: F(1) = 1, F(2) = 1 F(3) = F(1) + F(2) = 2 Input: N = 6 Output: 8 Approach: The Matrix Exponentiation Method is already discussed before. The Doubling Method can be seen as an improvement
14 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the
4 min read
Sum of Fibonacci Numbers
Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i'th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... Examples : Input : n = 3Output : 4Explanation : 0 + 1 + 1 + 2 = 4 Input : n = 4Output : 7Explanation : 0 + 1 + 1 + 2 +
9 min read
Fibonacci Series
Program to Print Fibonacci Series
Ever wondered about the cool math behind the Fibonacci series? This simple pattern has a remarkable presence in nature, from the arrangement of leaves on plants to the spirals of seashells. We're diving into this Fibonacci Series sequence. It's not just math, it's in art, nature, and more! Let's dis
9 min read
Program to Print Fibonacci Series in Java
The Fibonacci series is a series of elements where the previous two elements are added to generate the next term. It starts with 0 and 1, for example, 0, 1, 1, 2, 3, and so on. We can mathematically represent it in the form of a function to generate the n'th Fibonacci number because it follows a con
6 min read
Print the Fibonacci sequence - Python
To print the Fibonacci sequence in Python, we need to generate a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is the sum of the two previous num
5 min read
C Program to Print Fibonacci Series
The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers are 0 and 1 which are used to generate the whole series. Example Input: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3.
4 min read
JavaScript Program to print Fibonacci Series
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. The recurrence relation defines the sequence Fn of Fibonacci numbers: Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1 Examples: Input :
4 min read
Length of longest subsequence of Fibonacci Numbers in an Array
Given an array arr containing non-negative integers, the task is to print the length of the longest subsequence of Fibonacci numbers in this array.Examples: Input: arr[] = { 3, 4, 11, 2, 9, 21 } Output: 3 Here, the subsequence is {3, 2, 21} and hence the answer is 3.Input: arr[] = { 6, 4, 10, 13, 9,
5 min read
Last digit of sum of numbers in the given range in the Fibonacci series
Given two non-negative integers M, N which signifies the range [M, N] where M ? N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output:
5 min read
K- Fibonacci series
Given integers 'K' and 'N', the task is to find the Nth term of the K-Fibonacci series. In K - Fibonacci series, the first 'K' terms will be '1' and after that every ith term of the series will be the sum of previous 'K' elements in the same series. Examples: Input: N = 4, K = 2 Output: 3 The K-Fibo
7 min read
Fibonacci Series in Bash
Prerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples: Input : 5 Output : Fibonacci Series is : 0 1 1 2 3 Input :4 Output : Fibonacci Series is : 0 1 1 2 The Fibonacci numbers are the numbers in the following integer sequence . 0, 1, 1, 2
1 min read
R Program to Print the Fibonacci Sequence
The Fibonacci sequence is a series of numbers in which each number (known as a Fibonacci number) is the sum of the two preceding ones. The sequence starts with 0 and 1, and then each subsequent number is the sum of the two previous numbers. The Fibonacci sequence has many applications in various fie
3 min read