The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence typically goes: 0, 1, 1, 2, 3, 5, 8, 13, 21, etc. This document provides an efficient implementation of the Fibonacci sequence using dynamic programming.
Program Structure
- Input: An integer
n
representing the position in the Fibonacci sequence. - Output: The
n
th Fibonacci number. - Dynamic Programming: The program uses an array to store previously computed Fibonacci numbers to avoid redundant calculations.
C++ Code
#include <iostream>
#include <vector>
using namespace std;
// Function to calculate the nth Fibonacci number using dynamic programming
int fibonacci(int n) {
// Create an array to store Fibonacci numbers
vector<int> fib(n + 1);
// Base cases
fib[0] = 0;
if (n >= 1) {
fib[1] = 1;
}
// Fill the array using the bottom-up approach
for (int i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
// Return the nth Fibonacci number
return fib[n];
}
int main() {
int n;
// Input the position in the Fibonacci sequence
cout << "Enter the position in the Fibonacci sequence: ";
cin >> n;
// Calculate the nth Fibonacci number
int result = fibonacci(n);
// Output the result
cout << "The " << n << "th Fibonacci number is: " << result << endl;
return 0;
}
Explanation of the Code
The code consists of the following main components:
- Input Handling: The program prompts the user to enter the position
n
in the Fibonacci sequence. - Fibonacci Calculation: The
fibonacci
function uses dynamic programming to compute Fibonacci numbers. An arrayfib
stores the Fibonacci numbers up ton
. - Base Cases: The first two Fibonacci numbers (0 and 1) are initialized as base cases.
- Dynamic Programming Logic: The function iterates from 2 to
n
to fill the array using the recurrence relation:fib[i] = fib[i - 1] + fib[i - 2]
. - Output: The program displays the
n
th Fibonacci number computed.
Conclusion
This program efficiently computes the Fibonacci sequence using dynamic programming techniques, demonstrating how to avoid redundant calculations through memoization. This approach significantly improves the time complexity compared to the naive recursive solution.