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 – O(2^n) time and O(n) space
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(2^n)
Auxiliary Space: O(n), due to recursion stack
[Expected Approach-1] Memoization Approach – O(n) time and O(n) space
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 – O(n) time and O(n) space
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 – O(n) time and O(1) space
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: 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:
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 = . 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:
For more detail for this approach, please refer to our article “Find nth Fibonacci number using Golden ratio“
Related Articles: