Fibonacci Bottom Up Algorithm

The Fibonacci Bottom-Up Algorithm is a dynamic programming technique used to compute the Fibonacci numbers more efficiently compared to the traditional recursive method. This algorithm follows the bottom-up approach, meaning it starts from the base case(s) and builds up the solution using previously computed values. Instead of using recursion, it employs a simple loop to calculate the Fibonacci numbers, making it more time and memory efficient. The core idea behind this algorithm is to use an array or a list to store the Fibonacci numbers as they are calculated, so that they can be easily accessed when required. In this algorithm, the Fibonacci sequence is computed iteratively by initializing an array or list with the first two base values, F(0) = 0 and F(1) = 1. Then, a loop is run from the third Fibonacci number (i.e., F(2)) to the desired Fibonacci number (F(n)). In each iteration, the current Fibonacci number is calculated as the sum of the previous two Fibonacci numbers, and this value is then stored in the array or list. The previously computed Fibonacci numbers are used to calculate the new one, thus eliminating redundant calculations and significantly reducing the time complexity. The time complexity of the Fibonacci Bottom-Up Algorithm is O(n), which is a vast improvement over the O(2^n) complexity of the traditional recursive method, making it suitable for calculating larger Fibonacci numbers.
#include <iostream>
using namespace std;
int fib(int n)
{
	int res[3];
	res[0] = 0;
	res[1] = 1;
	for (int i = 2; i <= n; i++)
	{
		res[2] = res[1] + res[0];
		res[0] = res[1];
		res[1] = res[2];
	}
	return res[1];
}
int main(int argc, char const *argv[])
{
	int n;
	cout << "Enter n: ";
	cin >> n;
	cout << "Fibonacci number is ";
	cout << fib(n) << endl;
	return 0;
}

LANGUAGE:

DARK MODE: