C++ Program For Fibonacci Numbers
Last Updated :
16 May, 2025
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 they are used to generate the entire series.
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.
C++
#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;
}
The time complexity of the above code is O(2n), and it takes O(n) auxiliary space.
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 two numbers in the parameters to the recursive function.
C++
#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;
}
The time complexity of the above code is O(n), and it takes O(n) auxiliary space.
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:
C++
#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;
cout << fib(n);
return 0;
}
The time complexity of the above code is O(n), and it takes O(1) auxiliary space.
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
C++
#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;
cout << fib(n);
return 0;
}
The time complexity of the above code is O(log n), and it takes O(log n) auxiliary space.
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, 21Example:Input:
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 they are used to generate the entire series.Examples:Input: 5Output: 5Explanation: As 5 is the 5th Fibonacci number of series 0, 1, 1, 2, 3, 5
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 ContentPython 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: \varphi ={\fr
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 = 4Input : n = 4Output : 7Explanation : 0 + 1 + 1 + 2 + 3
9 min read
Fibonacci Series
Program to Print Fibonacci SeriesEver 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
8 min read
Program to Print Fibonacci Series in JavaThe Fibonacci series is a series of elements where the previous two elements are added to generate the next term. It starts with 0 and 1, for example, 0, 1, 1, 2, 3, and so on. We can mathematically represent it in the form of a function to generate the n'th Fibonacci number because it follows a con
5 min read
Print the Fibonacci sequence - PythonTo print the Fibonacci sequence in Python, we need to generate a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is the sum of the two previous num
5 min read
C Program to Print Fibonacci SeriesThe 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.ExampleInput: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3.In
4 min read
JavaScript Program to print Fibonacci SeriesThe 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 = 1Examples:Input : 5
4 min read
Length of longest subsequence of Fibonacci Numbers in an ArrayGiven 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 seriesGiven 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 seriesGiven 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 BashPrerequisite: 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 SequenceThe 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
2 min read