The Wayback Machine - https://web.archive.org/web/20241129130956/https://www.geeksforgeeks.org/cpp-program-for-fibonacci-numbers/
Open In App

C++ Program For Fibonacci Numbers

Last Updated : 14 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: 5
Output: 5
Explanation: As 5 is the 5th Fibonacci number of series 0, 1, 1, 2, 3, 5, 8, 13…. (0-based indexing)

Input: 1
Output: 1
Explanation: As 1 is the 1st Fibonacci number of series 0, 1, 1, 2, 3, 5, 8, 13…. (0-based indexing)

Following are the different ways to find the given term of the Fibonacci series in C++:

Using Recursion

The simplest way to find the nth Fibonacci number is by using recursion. In this approach, we define a function that returns the nth Fibonacci number based on the relation: F(n) = F(n-1) + F(n-2), where the base cases are F(0) = 0 and F(1) = 1. If the input value is 0 or 1, the function directly returns the input. Otherwise, it recursively calls itself with n-1 and n-2 to compute the result.

Code Implementation

C++
// C++ Program to find the nth fibonacci number using
// recursion
#include <bits/stdc++.h>
using namespace std;

int fib(int n) {

    // If n is 1 or 0, then return n, works for 0th
      // and 1st terms
    if (n <= 1)
        return n;

    // Recurrence relation to find the rest of the
      // terms
    return fib(n - 1) + fib(n - 2);
}

int main() {
    int n = 5;
  
      // Finding nth term
    cout << fib(n);
    return 0;
}

Output
5

Time Complexity: O (2n), where n is the number of term to find.
Auxiliary Space: O (n)

Optimization of Recursion Method

The complexity of the above method is very high as it is calculating all the previous fibonacci numbers for each recursive call. Due to this, previous fibonacci numbers are being calculated multiple times. We can avoid this by passing the previous numbers as parameters to the recursive function.

C++
// C++ Program to print the nth Fibonacci number using
// tail recursion
#include <iostream>
using namespace std;

// Helper function to find the nth fibonacci number
// using recursion
int fibHelper(int n, int prev2, int prev1) {
  
    // When n reaches 0, return prev2
    if (n == 0) {
        return prev2;
    }
  
    // When n reaches 1, return prev1
    if (n == 1) {
        return prev1;
    }
    
    // Recursive call with updated parameters to find
      // rest of the fibonacci numbers
    return fibHelper(n - 1, prev1, prev2 + prev1);
}

int fib(int n) {

      // Calling recursive function
    return fibHelper(n, 0, 1);
}

int main() {
    int n = 5;

    // Finding the nth Fibonacci number
    cout << fib(n);
    return 0;
}

Output
5

Time Complexity: O (n), where n is the number of term to find.
Auxiliary Space: O (n)

Using Loops

We can also find nth Fibonacci number using loops. In this approach, we keep two variables to keep the track of the last two Fibonacci numbers. We run a loop that runs in which we add the last two number variables to find the current term and then update these variables with current term and move to find the next term. We do that till we find the nth term.

Code Implementation

C++
// C++ Program to find the nth fibonacci number using
// loops
#include <bits/stdc++.h>
using namespace std;

int fib(int n) {
  
      // For 0th and 1st term
    if (n <= 1)
        return n;
    
      // Variable to store the last two terms
    int prev1 = 1, prev2 = 0;
      
      // Variable that stores the current fibonacci term
      int curr;

    // Calculating the next fibonacci number by using
      // the previous two number
    for (int i = 2; i <= n; i++) {
        curr = prev1 + prev2;
        prev2 = prev1;
        prev1 = curr;
    }
    return curr;
}

int main() {
    int n = 5;
    
      // Finding the nth fibonacci number
    cout << fib(n);
    return 0;
}

Output
5

Time Complexity: O(n), where n is the number of term to find.
Auxiliary Space: O(1)

Using Matrix Exponentiation

In this approach, the Fibonacci series is represented as a transformation matrix using the relation for Fibonacci Sequence is F(n) = F(n – 1) + F(n – 2) starting with F(0) = 0 and F(1) = 1 .It allows us to calculate the nth term efficiently by raising the matrix to the (n-1)th power. We use matrix exponentiation method which is used to calculate a matrix raised to a power efficiently.

Code Implementation

C++
// C++ Program to find the nth fibonacci number using
// loops
#include <bits/stdc++.h>
using namespace std;

// Function to multiply 2 * 2 matrix
void multiply(vector<vector<int>> &m1,
              vector<vector<int>> &m2) {
  
      // Matrix to store result
      vector<vector<int>> res(2, vector<int>(2));
    res[0][0] = m1[0][0] * m2[0][0]
          + m1[0][1] * m2[1][0];
    res[0][1] = m1[0][0] * m2[0][1]
          + m1[0][1] * m2[1][1];
    res[1][0] = m1[1][0] * m2[0][0]
          + m1[1][1] * m2[1][0];
    res[1][1] = m1[1][0] * m2[0][1]
          + m1[1][1] * m2[1][1];

    // Copying Multiplied matrix to m1
    m1[0][0] = res[0][0];
    m1[0][1] = res[0][1];
    m1[1][0] = res[1][0];
    m1[1][1] = res[1][1];
}

// Calculating the power(mat,n) in log n time
// using matrix exponentiation
void power(vector<vector<int>> &m, int n) {
    
    // Base case
    if(n == 0 || n == 1)
       return;
  
    // Identity matrix
     vector<vector<int>> i = {{1, 1},
                                {1, 0}};
    
    power(m, n / 2);
    multiply(m, m);
    
    if (n % 2 != 0)
        multiply(m, i);
}

int fib(int n) {
    
    // For 0th and 1st term
    if (n < 2)
        return n;
    
    // Representing fibonacci series as matrix
    vector<vector<int>> m = {{1, 1},
                                {1, 0}};

    // Finding (n - 1)th power of matrix m
    power(m, n - 1);
    
    // Returning nth fibonacci number
    return m[0][0];
}

int main() {
    int n = 5;

    // Finding nth fibonacci number
    cout << fib(n);
    return 0;
}

Output
5

Time Complexity: O(log n), where n is the number of term to find.
Auxiliary Space: O(log n)



Previous Article
Next Article

Similar Reads

Check if a M-th fibonacci number divides N-th fibonacci number
Given two numbers M and N, the task is to check if the M-th and N-th Fibonacci numbers perfectly divide each other or not.Examples: Input: M = 3, N = 6 Output: Yes F(3) = 2, F(6) = 8 and F(6) % F(3) = 0 Input: M = 2, N = 9 Output: Yes A naive approach will be to find the N-th and M-th Fibonacci numbers and check if they are perfectly divisible or n
8 min read
Check if sum of Fibonacci elements in an Array is a Fibonacci number or not
Given an array arr[] containing N elements, the task is to check if the sum of Fibonacci elements of the array is a fibonacci number or not.Examples: Input: arr[] = {2, 3, 7, 11} Output: Yes Explanation: As there are two Fibonacci numbers in the array i.e. 2 and 3. So, the sum of Fibonacci numbers is 2 + 3 = 5 and 5 is also a Fibonacci number. Inpu
7 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 Output : 144 Input : a = 8, b = 37 Output : 50731415
8 min read
C++ Program To Find 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 Output: 88 N = 5, So the fibonacci series will be gener
4 min read
Program to print first n Fibonacci Numbers | Set 1
Given an integer N. The task is to find the first N Fibonacci numbers. Examples :  Input: n = 3Output: 0 1 1 Input: n = 7Output: 0 1 1 2 3 5 8 Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.  Program to print first 'n' Fibonacci Numbers using recursion:Below is the idea to solve the problem: Use recursion to fin
7 min read
Program to find Prime Fibonacci Numbers till N
Given a number, find the numbers (smaller than or equal to n) which are both Fibonacci and prime. Examples: Input : n = 40 Output: 2 3 5 13 Explanation : Here, range(upper limit) = 40 Fibonacci series upto n is, 1, 1, 2, 3, 5, 8, 13, 21, 34. Prime numbers in above series = 2, 3, 5, 13. Input : n = 100 Output: 2 3 5 13 89 Explanation : Here, range(u
8 min read
Print first n Fibonacci Numbers using direct formula
Given a number n, the task is to print first n Fibonacci numbers. Prerequisite: Program to print first n Fibonacci Numbers | Set 1 Examples: Input : 7 Output :0 1 1 2 3 5 8 Input : 5 Output :0 1 1 2 3 N-th Fibonacci Number = [(1 + ?5)n - (1 - ?5)n)] / [2n * ?5] Below is the implementation. C/C++ Code // C++ code to print fibonacci // numbers till n
4 min read
Generating large Fibonacci numbers using boost library
In our previous post on fibonacci series, we have seen many approaches to generate fibonacci numbers. In this approach, we shall be generating fibonacci numbers with the help of boost library. The program simply uses the "boost/multiprecision/cpp_int.hpp" boost library in which big_int is defined. The fibonacci numbers beyond the range of long long
5 min read
Deriving the expression of Fibonacci Numbers in terms of golden ratio
Prerequisites: Generating Functions, Fibonacci Numbers, Methods to find Fibonacci numbers. The method of using Generating Functions to solve the famous and useful Fibonacci Numbers' recurrence has been discussed in this post. The Generating Function is a powerful tool for solving a wide variety of mathematical problems, including counting problems.
4 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's suppose F(x, k, n) be the number of ways to for
8 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 fibonacci numbers and using the previous two to s
4 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 Explanation: 0 + 1 + 1 + 4 = 6 Input: N = 6 Outpu
11 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, the sequence Fn of Fibonacci numbers is defined
12 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 calculate fib(l) + fib(l + 1) + fib(l + 2) + ..... + fib(r
8 min read
Sum of all Non-Fibonacci numbers in a range for Q queries
Given Q queries containing ranges in the form of [L, R], the task is to find the sum of all non-fibonacci numbers for each range in the given queries.Examples: Input: arr[][] = {{1, 5}, {6, 10}} Output: 4 32 Explanation: Query 1: In the range [1, 5], only 4 is a non-fibonacci number. Query 2: In the range [6, 10], 6, 7, 9 and 10 are the non-fibonac
8 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, 25 } Output: 1 Here, the subsequence is {1} and h
5 min read
Remove all nodes from a Doubly Linked List containing Fibonacci numbers
Given a doubly linked list containing N nodes, the task is to remove all the nodes from the list which contains Fibonacci numbers.Examples: Input: DLL = 15 <=> 16 <=> 8 <=> 7 <=> 13 Output: 15 <=> 16 <=> 7 Explanation: The linked list contains two fibonacci numbers 8 and 13. Hence, these nodes have been deleted.I
15 min read
Find the numbers present at Kth level of a Fibonacci Binary Tree
Given a number K, the task is to print the fibonacci numbers present at Kth level of a Fibonacci Binary Tree.Examples: Input: K = 3 Output: 2, 3, 5, 8 Explanation: Fibonacci Binary Tree for 3 levels: 0 / \ 1 1 /\ / \ 2 3 5 8 Numbers present at level 3: 2, 3, 5, 8 Input: K = 2 Output: 1, 1 Explanation: Fibonacci Binary Tree for 2 levels: 0 / \ 1 1 N
12 min read
Sum of numbers in the Kth level of a Fibonacci triangle
Given a number K, the task is to find the sum of numbers at the Kth level of the Fibonacci triangle.Examples: Input: K = 3 Output: 10 Explanation: Fibonacci triangle till level 3: 0 1 1 2 3 5 Sum at 3rd level = 2 + 3 + 5 = 10 Input: K = 2 Output: 2 Explanation: Fibonacci triangle till level 3: 0 1 1 Sum at 3rd level = 1 + 1 = 2 Approach: Till Kth l
6 min read
Array range queries to count the number of Fibonacci numbers with updates
Given an array arr[] of N integers, the task is to perform the following two queries: query(start, end): Print the number of fibonacci numbers in the subarray from start to endupdate(i, x): Add x to the array element referenced by array index i, that is: arr[i] = x Examples: Input: arr = { 1, 2, 3, 4, 8, 9 } Query 1: query(start = 0, end = 4) Query
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 to 90 is {1, 89}Input: N = 74 Output: -1 Approach
6 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 array.Input: arr[] = {2, 4, 7, 8, 9, 11} Output: 4
9 min read
Count of numbers whose difference with Fibonacci count upto them is atleast K
Prerequisites: Binary SearchGiven two positive integers N and K, the task is to count all the numbers that satisfy the following conditions: If the number is num, num ? N.abs(num - count) ? K where count is the count of fibonacci numbers upto num. Examples: Input: N = 10, K = 3 Output: 2 Explanation: 9 and 10 are the valid numbers which satisfy the
9 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 K-minimum fibonacci numbers is 7 Product of K-mini
11 min read
Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range
Prerequisites: Digit DP Given a range [L, R], the task is to count the numbers in this range having the difference between, the sum of digits at even positions and sum of digits at odd positions, as a Fibonacci Number. Note: Consider the position of the least significant digit in the number as an odd position. Examples: Input: L = 1, R = 10 Output:
15 min read
Count numbers divisible by K in a range with Fibonacci digit sum for Q queries
Given an array arr[][] containing Q queries and an integer K where each query consists of a range [L, R], the task is to find the count of integers in the given range whose digit sum is a Fibonacci number and divisible by K.Examples: Input: arr[][] = { {1, 11}, {5, 15}, {2, 24} }, K = 2 Output: 3 2 5 Explanation: For query 1: 2, 8 and 11 are the nu
11 min read
Count of total subarrays whose sum is a Fibonacci Numbers
Given an array arr[] of N integers, the task is to count total number of subarrays whose sum is a Fibonacci Number.Examples: Input: arr[] = {6, 7, 8, 9} Output: 3 Explanation: The subarray whose sum is fibonacci numbers are: 1. {6, 7}, sum = 13 (5 + 8) 2. {6, 7, 8}, sum = 21 (8 + 13) 3. {8}, sum = 8 (3 + 5)Input: arr[] = {1, 1, 1, 1} Output: 4 Expl
7 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: 6 Explanation: We need to find F3 + F4 + F5 + F6 +
5 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 not possible to select {5 + 5 + 3} because 5 appears
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}. Therefore, array elements which are both composite as well
11 min read
Practice Tags :
three90RightbarBannerImg