Please Answer In Details Show all Steps:
Implement two C++ programs to generate Fibonacci sequence (one using recursion, one using non-recursion structure); analyze their complexity using O notation
Iterative (non-recursive)
#include<iostream>
#include<stdio.h>
using namespace std;
int fibonacciiterative(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
int a = 0;
int b = 1;
int c = 0;
for (int i = 2; i <= n; ++i)
{
c = a + b;
a = b;
b = c;
}
return c;
}
int main(){
cout <<"The seventh fibonacci number is: " << fibonacciiterative(7) << endl;
}
===================================================================================
Recursive Fibonacci
#include <iostream>
using namespace std;
int fibonacciRecursive(int x) {
if (x == 0)
return 0;
else if(x==1)
return 1;
else
return
fibonacciRecursive(x-1)+fibonacciRecursive(x-2);
}
int main() {
cout <<"The seventh fibonacci number is: "
<< fibonacciRecursive(7) << endl;
}
===============================================================================
Adding Image and Output:-
Time Complexity :
For Recursive Implementation: T(n) = T(n-1) + T(N-2) , which tends
to exponential time complexity
=> O(2n)
For Iterative Implementation: Time complexity is Linear =>
O(n)
Get Answers For Free
Most questions answered within 1 hours.