What's wrong with this code? Why prints negative numbers while Fibonacci sequence doesn't include them? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What's wrong with this code? Why prints negative numbers while Fibonacci sequence doesn't include them?

#include <iostream> using namespace std; int fibonacci (int length) { int a[length]; a[-1]=0, a[0]=0; a[1]=1; for (int n=2;n<=length+2;n++) { a[n]=a[n-1]+a[n-2]; cout << a[n]<<", "; }; return 0; } // F(n)=F(n-1)+F(n-2) int main() { int x; cin >> x; fibonacci (x); return 0; }

3rd Dec 2016, 1:59 PM
Georgios Bariamai
Georgios Bariamai - avatar
5 Answers
+ 3
Commonly such variables are 32 bit values and have a maximum possible value of 2^31 - 1. That equals 2,147,483,647 which is some way short of your goal of reaching 1,000 digits. The 47th Fibonacci number is the first number to exceed 2,147,483,647. According to Wolfram Alpha, the value is2,971,215,073. When your program attempts to calculate such a number it suffers from integer overflow, because the true value cannot be stored in an int. You could try to analyse exactly what happens when you overflow, why you see negative values, but it really doesn't get you very far. Simply put, what you are attempting is clearly impossible with int. In order to reach 1,000 digits you need to use a big integer type. None of the built-in types can handle numbers as large as you intend to handle.
3rd Dec 2016, 2:21 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 3
You can use long long int it has a range 2*(2^62-1). You can use this. It will generate positive value for long range. but not to 1000. here it is #include <iostream> using namespace std; int fibonacci (int length) { long long int a[length]; a[-1]=0, a[0]=0; a[1]=1; for (int n=2;n<=length+2;n++) { a[n]=a[n-1]+a[n-2]; cout << a[n]<<", "; } return 0; } // F(n)=F(n-1)+F(n-2) int main() { int x; cin >> x; fibonacci (x); return 0; }
3rd Dec 2016, 2:29 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 2
I did not get negative number. On which range you get negative number. Please explain
3rd Dec 2016, 2:11 PM
Aditya kumar pandey
Aditya kumar pandey - avatar
+ 1
I've thought of that and I made a template setting a variable type "T" in order to fix that, but nothing changed... At least, I know that I cannot do something further from that. Thanks!
3rd Dec 2016, 2:24 PM
Georgios Bariamai
Georgios Bariamai - avatar
0
If you set x=1000, you will notice that prints negative numbers
3rd Dec 2016, 2:12 PM
Georgios Bariamai
Georgios Bariamai - avatar