Open In App

Nth Fibonacci Number

Last Updated : 14 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 Java Python C# JavaScript

Output
5

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 Java Python C# JavaScript

Output
5

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 Java Python C# JavaScript

Output
5

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 Java Python C# JavaScript

Output
5

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: (1110)\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:
(1110)n1=(F(n)F(n1)F(n1)F(n2))\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 Java Python C# JavaScript

Output
5

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 = ϕ=1+52\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)=ϕn(1ϕ)n5F(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: 



Next Article

Similar Reads

three90RightbarBannerImg