xxxxxxxxxx
// Fibonacci serise using time complexity of O(n)=n or optimal time complexity
#include <iostream>
using namespace std;
int fArr[10];
int Fibo(int n){
if(n <= 1){ //base class. Setting the first 2 index value to 0 &1
fArr[n] = n;
return n;
}else{
if(fArr[n-2] == -1){//if no values in the array then by default -1 will be there as default value
fArr[n-2] = Fibo(n-2); // making a recursive call if the value doesn't present in the array
}
if(fArr[n-1] == -1){
fArr[n-1] = Fibo(n-1);
}
return fArr[n-2] + fArr[n-1];
}
}
int main() {
int term;
cout << "Enter Your Fibonacci Term No: " << endl;
cin >> term;
for(int i=0; i<term; i++){ //making every index value of -1
fArr[i]=-1;
}
cout << "The Result Of Fibonacci Serise is: " << Fibo(term) << endl;
return 0;
}
xxxxxxxxxx
def fib (n):
if n == 0 or n ==1:
return n
else:
return fib(n-2) + fib(n-1)
#n = int(input("please enter a number "))
n=10
for index,num in enumerate(range(n+1)):
print(f"F{index} :", fib(num))
xxxxxxxxxx
int fib (int n) {
if (n < 2)
return 1;
return fib(n-1) + fib(n-2);
}
xxxxxxxxxx
def fibonacci(n):
•if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
n = int(input())
result = fibonacci(n)
print(result)
xxxxxxxxxx
function fib(n) {
if (n === 1 || n === 0)
return n
return fib(n - 1) + fib(n - 2)
}
console.log('fib:', fib(9)) // [Log]: fib: 34
/*
Time complexity O(2^n)
Space complexity O(n)
Since fib(n-1) gets evaluated completely before fib(n-2),
there will never be more than n levels of recursion.
*/