Fibonacci numbers form a sequence such that each number is the sum of the two preceding ones.
Fibonacci numbers start from 0, 1.
DP Based Solution -
Fibonacci numbers start from 0, 1.
and
for n > 1
So the series is
To find nth fibonacci number
Recursive Solution -
#include<stdio.h>
int count;
int fib(int no)
{
count++;
if(no<=1)
return no;
else
return fib(no-1)+fib(no-2);
}
void main()
{
int num;
printf("Enter which fibbonacci number you want to find out\n");
scanf("%d",&num);
printf("The %dth fibbonacci number is %d",num,fib(num-1));
printf("Recursion=%d",count);
}
This program has high complexity we can use DP to reduce complexity.DP Based Solution -
#include<stdio.h>
int lookup[1000];
void initialize()
{
int i;
for(i=0;i<1000;i++)
lookup[i]=-1;
}
int fibo(int num)
{
if(lookup[num]!=-1) //if number found in look up table than return
return lookup[num];
else //number not found in look up table
{
if(num<=1)
lookup[num]=num;
else //calculate the number and store in look up table than return
lookup[num]=fibo(num-1)+fibo(num-2);
}
return lookup[num];
}
void main()
{
int num,i;
printf("Enter which fibbonacci number you want to find out\n");
scanf("%d",&num);
initialize();
printf("The %dth fibbonacci number is %d",num,fibo(num-1));
}
No comments:
Post a Comment