+ 2
Why this Fibonacci program won't work for n=50 or more
This the code for generating nth Fibonacci number. The code works fine for small numbers and for numbers like 50 or more it is giving negative values. Do help. https://code.sololearn.com/cZ85E1DbwOs2/?ref=app
4 Respostas
+ 5
Look I wrote this program in python:
https://code.sololearn.com/c08VfLHKng0H/?ref=app
+ 4
#include <stdio.h>
int main() {
int t1 = 0, t2 = 1, nextTerm = 0, n;
printf("Enter a positive number: ");
scanf("%d", &n);
// displays the first two terms which is always 0 and 1
printf("Fibonacci Series: %d, %d, ", t1, t2);
nextTerm = t1 + t2;
while (nextTerm <= n) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
return 0;
}
+ 4
Your recursive version of Fibonacci has an exponential time complexity. SL playground has some time limit for the codes to run . In your case , it works perfect till n=38 .
For numbers >38 , it is taking too much time .
+ 1
The fibonacci function is causing integer overflow as the number grows beyond the largest value that a signed integer can hold. That causes it to wrap around into negative numbers because it starts using the highest bit, which is the negative flag. Try changing the function type and related internal variables to unsigned int, or long, or unsigned long.
EDIT: A shorter way is to just change the format specifier to %u in the printf to show output as unsigned:
printf("\n%dth fibonacci %u\n", n, fibonacci(n));
This adjustment would be necessary anyway if you were to change the function type to unsigned int.