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: [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 +
12 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 get the next element, starting with 0 and 1. In this article, we will learn how to print Fibonacci Series in Java up to the N term, where N is the given number. Examples of Fibonacci Series in JavaInput: N = 1
5 min read
Python Program to Print the Fibonacci sequence
The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation. Fn = Fn-1 + Fn-2 with seed values : F0 = 0 and F1 = 1. Table of Content F
3 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
Variations of Fibonacci number
Generalized Fibonacci Numbers
We all know that Fibonacci numbers (Fn) are defined by the recurrence relation Fibonacci Numbers (Fn) = F(n-1) + F(n-2) with seed values F0 = 0 and F1 = 1 Similarly, we can generalize these numbers. Such a number sequence is known as Generalized Fibonacci number (G). Generalized Fibonacci number (G)
10 min read
The Magic of Fibonacci Numbers
Fibonacci Series: The word sounds familiar, right? An Easy To Understand sequence represented as 0 1 1 2 3 5 8 13.... where each number is the sum of the preceding two numbers, with the series starting from 0, 1. But, did you ever realise how magical these numbers are? Let's get deeper into these nu
3 min read
Alternate Fibonacci Numbers
Give a number N, print alternate fibonacci numbers till n-th Fibonacci. Examples: Input : N = 7 Output : 0 1 3 8 Input : N = 15 Output : 0 1 3 8 21 55 144 377 Read method 2 in the following article : fibonacci number Approach:Using dynamic programming approach. Keep storing the previously calculated
4 min read
Non Fibonacci Numbers
Given a positive integer n, the task is to print the nth non-Fibonacci number. The Fibonacci numbers are defined as: Fib(0) = 0Fib(1) = 1for n >1, Fib(n) = Fib(n-1) + Fib(n-2)First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, …….. Examples: Input : n = 2Output : 6Input
15 min read
Zeckendorf's Theorem (Non-Neighbouring Fibonacci Representation)
Zeckendorf's theorem states that every positive integer can be written uniquely as a sum of distinct non-neighbouring Fibonacci numbers. Two Fibonacci numbers are neighbours if they one come after other in Fibonacci Sequence (0, 1, 1, 2, 3, 5, ..). For example, 3 and 5 are neighbours, but 2 and 5 ar
8 min read
Matrix Exponentiation
Matrix Exponentiation is one of the most used techniques in competitive programming. In this post, we will provide a detailed overview about what is Matrix Exponentiation, its implementation, uses, etc. Table of Content What is Matrix Exponentiation?Idea behind Matrix ExponentiationUse Cases of Matr
15+ min read
Fibonacci Coding
Fibonacci coding encodes an integer into binary number using Fibonacci Representation of the number. The idea is based on Zeckendorf’s Theorem which states that every positive integer can be written uniquely as a sum of distinct non-neighboring Fibonacci numbers (0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
12 min read
Fibonacci Search
Given a sorted array arr[] of size n and an element x to be searched in it. Return index of x if it is present in array else return -1. Examples: Input:  arr[] = {2, 3, 4, 10, 40}, x = 10Output: 3Element x is present at index 3. Input: arr[] = {2, 3, 4, 10, 40}, x = 11Output:  -1Element x is not
15+ min read
Cassini’s Identity
Given a number N, the task is to evaluate below expression. Expected time complexity is O(1). f(n-1)*f(n+1) - f(n)*f(n) Where f(n) is the n-th Fibonacci number with n >= 1. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ...........i.e. (considering 0 as 0th Fibonacci number) Examples :
3 min read
Hosoya's Triangle
The Fibonacci triangle or Hosoya's triangle is a triangular arrangement of numbers based on Fibonacci numbers. Each number is the sum of two numbers above in either the left diagonal or the right diagonal. The first few rows are: The numbers in this triangle follow the recurrence relations Relation
11 min read
Find the previous fibonacci number
Given a Fibonacci number N, the task is to find the previous Fibonacci number.Examples: Input: N = 8 Output: 5 5 is the previous fibonacci number before 8.Input: N = 5 Output: 3 Approach: The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is div
2 min read
Minimum Fibonacci terms with sum equal to K
Given a number k, find the required minimum number of Fibonacci terms whose sum equal to k. We can choose a Fibonacci number multiple times. Examples: Input : k = 4Output : 2Fibonacci term added twice that is2 + 2 = 4. Other combinations are 1 + 1 + 2. 1 + 1 + 1 + 1Among all cases first case has the
7 min read
Sum of Fibonacci Numbers in a range
Given a range [l, r], the task is to find the sum fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r) where fib(n) is the nth Fibonacci number. Examples: Input: l = 2, r = 5 Output: 11 fib(2) + fib(3) + fib(4) + fib(5) = 1 + 2 + 3 + 5 = 11 Input: l = 4, r = 8 Output: 50 Naive approach: Simply calculat
8 min read
Find the sum of first N odd Fibonacci numbers
Given a number, N. Find the sum of first N odd Fibonacci numbers. Note: The answer can be very large so print the answer modulo 10^9+7. Examples: Input : N = 3Output : 5Explanation : 1 + 1 + 3Input : 6Output : 44Explanation : 1 + 1 + 3 + 5 + 13 + 21Approach: Odd Fibonacci series is: 1, 1, 3, 5, 13,
9 min read
Even Fibonacci Numbers Sum
Given a limit, find the sum of all the even-valued terms in the Fibonacci sequence below given limit.The first few terms of Fibonacci Numbers are, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ,... (Even numbers are highlighted).Examples : Input : limit = 8 Output : 10 Explanation : 2 + 8 = 10 Inpu
6 min read
Largest and smallest Fibonacci numbers in an Array
Given an array arr[] of N positive integers, the task is to find the minimum (smallest) and maximum (largest) Fibonacci elements in the given array. Examples:Input: arr[] = 1, 2, 3, 4, 5, 6, 7 Output: 1, 5 Explanation : The array contains 4 fibonacci values 1, 2, 3 and 5. Hence, the maximum is 5 and
15+ min read
Some other problems on Fibonacci Numbers
Largest subset whose all elements are Fibonacci numbers
Given an array arr[], the task is to find the largest subset from array that contain elements which are Fibonacci numbers. Examples : Input: arr[] = [1, 4, 3, 9, 10, 13, 7]Output: [1, 3, 13]Explanation: The output three numbers are the only Fibonacci numbers in array. Input: arr[] = [0, 2, 8, 5, 2,
10 min read
Count Fibonacci numbers in given range in O(Log n) time and O(1) space
Given a range, count Fibonacci numbers in given range. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Example : Input: low = 10, high = 100 Output: 5 There are five Fibonacci numbers in given range, the numbers are 13, 21, 34, 55 and 89. Input: low = 10, high = 20 O
5 min read
Number of ways to represent a number as sum of k fibonacci numbers
Given two numbers N and K. Find the number of ways to represent N as the sum of K Fibonacci numbers. Examples: Input : n = 12, k = 1 Output : 0 Input : n = 13, k = 3 Output : 2 Explanation : 2 + 3 + 8, 3 + 5 + 5. Approach: The Fibonacci series is f(0)=1, f(1)=2 and f(i)=f(i-1)+f(i-2) for i>1. Let
8 min read
Pair of fibonacci numbers with a given sum and minimum absolute difference
Given an integer N(less than 10^6), the task is to find a pair of Fibonacci numbers whose sum is equal to the given N, and the absolute difference between the chosen pair is minimum. Print -1 if there is no solution. Examples: Input: N = 199 Output: 55 144 Explanation 199 can be represented as sum 5
8 min read
Sum of squares of Fibonacci numbers
Given a positive integer N. The task is to find the sum of squares of all Fibonacci numbers up to N-th Fibonacci number. That is, f02 + f12 + f22+.......+fn2 where fi indicates i-th fibonacci number. Fibonacci numbers: f0=0 and f1=1 and fi=fi-1 + fi-2 for all i>=2.Examples: Input: N = 3 Output: 6
11 min read
Sum of Fibonacci numbers at even indexes upto N terms
Given a positive integer N, the task is to find the value of F2 + F4 + F6 +.........+ F2n upto N terms where Fi denotes the i-th Fibonacci number.The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...... Examples: Input: n = 5 Outpu
15+ min read
Find two Fibonacci numbers whose sum can be represented as N
Given an even number N, the task is to find two Fibonacci numbers whose sum can be represented as N. There may be several combinations possible. Print only first such pair. If there is no solution then print -1.Examples: Input: N = 90 Output: 1, 89 Explanation: The first pair with whose sum is equal
6 min read
Count of ways in which N can be represented as sum of Fibonacci numbers without repetition
Given a number N, the task is to find the number of ways in which the integer N can be represented as a sum of Fibonacci numbers without repetition of any Fibonacci number. Examples: Input: N = 13Output: 3Explanation: The possible ways to select N as 13 are: {13} {8, 5} {8, 3, 2}. Note that it is no
10 min read
Count composite fibonacci numbers from given array
Given an array arr[] of size N, the task is to find the composite Fibonacci numbers present in the given array. Examples: Input: arr[] = {13, 55, 7, 3, 5, 21, 233, 144, 6}Output: 55 21 144Explanation: Composite array elements are {55, 21, 144, 6}. Fibonacci array elements are {55, 21, 144}. Therefor
11 min read
Remove all the fibonacci numbers from the given array
Given an array arr[] of N integers, the task is to remove all the fibonacci numbers present in the array.Examples: Input: arr[] = {4, 6, 5, 3, 8, 7, 10, 11, 14, 15} Output: 4 6 7 10 11 14 15 Explanation: The array contains 3 fibonacci data values 5, 3 and 8. These values have been removed from the a
9 min read
Minimize cost of converting all array elements to Fibonacci Numbers
Given an array arr[] consisting of N integers, the task is to minimize the cost of converting all array elements to a Fibonacci Number, where the cost of converting a number A to B is the absolute difference between A and B. Examples: Input: arr[] = {56, 34, 23, 98, 7}Output: 13Explanation:Following
8 min read
Find Index of given fibonacci number in constant time
We are given a Fibonacci number. The first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ..... We have to find the index of the given Fibonacci number, i.e. like Fibonacci number 8 is at index 6. Examples : Input : 13Output : 7Input : 34Output : 9Method 1 (Simple) : A simpl
10 min read
Program to find LCM of two Fibonacci Numbers
Given here are two positive numbers a and b. The task is to print the least common multiple of a'th and b'th Fibonacci Numbers.The first few Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ......Note that 0 is considered as 0’th Fibonacci Number.Examples: Input : a = 3, b = 12 Ou
8 min read
Sum of Fibonacci Numbers with alternate negatives
Given a positive integer n, the task is to find the value of F1 - F2 + F3 -..........+ (-1)n+1Fn where Fi denotes i-th Fibonacci number.Fibonacci Numbers: The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .... In mathematical terms
12 min read
Sum and product of K smallest and largest Fibonacci numbers in the array
Given an integer K and an array arr[] containing N integers, the task is to find the sum and product of K smallest and K largest fibonacci numbers in the array. Note: Assume that there are at least K fibonacci numbers in the array. Examples: Input: arr[] = {2, 5, 6, 8, 10, 11}, K = 2 Output: Sum of
11 min read