# Find the Nth Fibonacci number | C++

Here, we are going to learn **how to find the Nth Fibonacci number using Dynamic programming in C++**.

Submitted by Ritik Aggarwal, on November 07, 2018

**Problem:** Compute the N^{th} Fibonacci number

You are given a number N. You have to **find the N ^{th} Fibonacci number**. 0

^{th}Fibonacci number is 0 and first Fibonacci number is 1.

**Sample inputs:**

N = 0, answer is 0 N = 1, answer is 1 N = 5, answer is 5

**Basic Approach: Recursive approach**

int fibonacci(int N){ if(N == 0 || N == 1){ return N; } int ans = fibonacci(N-1) + fibonacci(N - 2); return ans; }

Now provided above is the basic recursive approach which takes **O(2^N)** time to compute as every call needs to call two other calls but if we already have the answers of two other calls in an array then we can directly use them.

**Top Down Approach:**

int fibonacciTopDown(int N, int strg[]){ if(N == 1 || N == 0){ return N; } if(strg[N] != 0){ return strg[N]; } int ans = fibonacciTopDown(N-1, strg) + fibonacciTopDown(N - 2, strg); strg[N] = ans; return ans; }

Now the top down approach also uses recursion but before returning the answer to the solution we store the answer in strg array so that if we needed the answer again then we could simply use that answer directly from our array. The time complexity of the program is **O(N)**.

**Bottom Up Approach:**

int fibonacciBottomUp(int N){ int strg[N + 1] = {0}; strg[0] = 0; strg[1] = 1; for(int i = 2;i<N+1;i++){ strg[i] = strg[i-1] + strg[i-2]; } return strg[N]; }

This is the Bottom Up approach with time complexity as **O(N)**. Now we have an iterative method to the recursive problem.

As seen above from the dp approaches we can very easily see that storage matrix or dp matrix has some meaning. For example, In the Fibonacci case, the **N ^{th}** index of strg matrix stores the

**N**fibonaaci number that's why we can very easily write this line strg[i] = strg[i-1] + strg[i-2].

^{th}As stated above start solving dp problems with recursion first and then proceed to dp. Try assigning some meaning to the storage matrix or dp matrix and formulate the correct equation.

**Code to find the Nth Fibonacci number using all given approaches **

#include <iostream> using namespace std; int fibonacci(int N){ if(N == 0 || N == 1){ return N; } int ans = fibonacci(N-1) + fibonacci(N - 2); return ans; } int fibonacciTopDown(int N, int strg[]){ if(N == 1 || N == 0){ return N; } if(strg[N] != 0){ return strg[N]; } int ans = fibonacciTopDown(N-1, strg) + fibonacciTopDown(N - 2, strg); strg[N] = ans; return ans; } int fibonacciBottomUp(int N){ int strg[N + 1] = {0}; strg[0] = 0; strg[1] = 1; for(int i = 2;i<N+1;i++){ strg[i] = strg[i-1] + strg[i-2]; } return strg[N]; } int main() { int N; cin >> N; int strg[N + 1] = {0}; cout << "The answer using recursive solution is " << fibonacci(N) << endl; cout << "The answer using Bottom up aproach is " << fibonacciBottomUp(N) << endl; cout << "The answer using Top down approach is " << fibonacciTopDown(N,strg) << endl; return 0; }

**Output**

8 The answer using recursive solution is 21 The answer using Bottom up aproach is 21 The answer using Top down approach is 21

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Bubble sort Algorithm, Flow Chart and C++ Code
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!