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: \begin{pmatrix}1 & 1 \\1 & 0 \end{pmatrix}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:
\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}
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 = \phi = \frac{1 + \sqrt{5}}{2}. 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: F(n) = \frac{\phi^n - (1 - \phi)^n}{\sqrt{5}}
For more detail for this approach, please refer to our article "Find nth Fibonacci number using Golden ratio"
Related Articles:
Introduction to Fibonacci Numbers
Introduction to Fibonacci Numbers
Properties of Fibonacci Numbers
Fibonacci Divisibility and GCD
Fibonacci series up to Nth term | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem