I am trying to generate Fibonacci series and provided the code for the same below. When I run this code for smaller values, it outputs correct results. However, when I try and calculate series for a number say ’50’, it out puts correct results upto the 47th number and result for 48,49 and 50th term are incorrect. I tried using unsigned long int as well but it did not correct the results. Can some please suggest what am I doing wrong here.
Thanks.
#include<stdio.h>
unsigned long long int fibr(unsigned long long int);
int main(){
unsigned long long int n;
printf("Enter a number\n");
scanf("%llu",&n);
//res=fibr(n);
while(n>=0){
printf("%llu\n",fibr(n));
n--;
}
}
unsigned long long int fibr(unsigned long long int n){
if((n==0)||(n==1))
return n;
else return fibr(n-1)+fibr(n-2);
}
‘After the suggestions , I incorporated unsigned long long int. Have modified the code above but now it gives a seg fault. Any hints please. I am not allowed to use any other library except the standards one available. ‘
Here’s the answer to your second question:
I think you had this problem from the beginning:
is an infinite loop since
nis an unsigned integer.nwill go negative due to the decrement. But since it’s unsigned, it will wrap around and cause a stack-overflow in your recursion.Also, your algorithm is probably slowest way to do this. It runs in exponential time. So it will take a very long time to run it when
nis big.A better way is just this:
This method will run in constant time. 🙂