Naive and Efficient way of displaying a fibonacci number

With larger the input more time it takes to complete, with this in consideration we have two algorithms to implement and two comparison to make between a naive and an efficient way for solving a fibonacci number. As the Italian mathematician was quite inquisitive with rabbit reproduction this algorithm “Fibonacci Series” was developed, which quite fascinating as we disclose the history.

I’ve written a C code with two function “naiveFib” and “efficientFib” both of these function does the same work but the function efficientFib works more faster than the naive one reducing time complexity to¬†O(n2)


#include <stdio.h>
unsigned int naiveFib(int n)
{
if(n==0){
return 0;
}
else if(n==1){
return 1;
}
else{
return ( naiveFib(n-1) + naiveFib(n-2) );
}
}
unsigned int efficientFib(int n){
/*Write your code here*/
int a=0,b=1,f=1,count=0;
for (int i = 0; i < n; i++)
{
/* code */
f=a+b;
a=b;
b=f;
// count+=1;
}
// printf("%d\n",count);
return f;
}

int main()
{
int n,i;
printf("Enter the limit of series: ");
scanf("%d",&n);
for(i=0;i<=n;i++)
{
// printf(" %d ",naiveFib(i));
printf(" %u ",efficientFib(i));
}
printf("\n");
}

For Helpful Doc please check Recursion Sample

For further codes please do refer to My Github


Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

*