If we want to compute Nth Fibonacci number F(n)=F(n-1)+F(n-2) .We can do it with iteration method and recursive method. if we do it with iterative method
#include<stdio.h>
main()
{
int a=0,b=1,c,i,n;
//clrscr();
printf("enter the limit of series\n");
scanf("%d",&n);
if(n==0)
printf("%d\n",a);
else
printf("%d\n%d\n",a,b);
for(i=2;i<=n;i++)
{
c=a+b;
printf("%d\n",c);
a=b;
b=c;
}
}
It takes O(n) time as it iterates from i=0 to N.
But with recursive method
int F(int i)
{
if (i < 1) return 0;
if (i == 1) return 1;
return F(i-1) + F(i-2);
}
The recurrence relation is
___________ 0 if(n<=0)
/___________ 1 if(n==1)
Fibonacci(n) ____/
\
\___________ Fibonacci(n-1)+Fibonacci(n-2)
So our problem for n = sub-problem of (n-1) + sub-problem of (n-2) hence our time function T(n) is as follows
T(n)=T(n-1)+T(n-2)+O(1)
T(n)={T(N-2)+T(n-3)}+T(n-2) since T(n-1)=T(n-2)+T(n-3) -------- equation(1)
from above you can see T(n-2) is calculated twice. If we expand the recursion tree for N=5 . The recursion tree is as follows
Fib(5)
|
_____________________/ \__________________
| |
Fib(4) + fib(3)
| |
_______/ \_______ ________/ \_______
| + | | + |
Fib(3) Fib(2) Fib(2) Fib(1)
| | |
_______/ \____ ____/ \_______ _______/ \_____
| + | | + | | + |
Fib(2) Fib(1) Fib(1) Fib(0) Fib(1) Fib(0)
_______/ \_______
| + |
Fib(1) Fib(0)
If we observe the recurrsion tree we find that Fib(1) is caliculated 5 times
Fib(2) is caliculated 3 times
Fib(3) is caliculated 2 times
So using recursion we are actually doing redundant computations . If you use iterative method these redudant calculations are avoided.
T(n)=T(n-1)+T(n-2)+1
From previous SO post Computational complexity of Fibonacci Sequence
complexity of program is approximately equal to bigoh(2power(n)) .
Since O(n) < O(2powerN) recursive method is not efficient.