M0113Y
M0113Y

Reputation: 13

Weird output as the numbers get bigger in Fibonacci sequence

I noticed in my fibonacci sequence that I'm getting negative numbers after a certain point:

267914296 433494437 701408733 1134903170
1836311903 -1323752223 512559680 -811192543 -298632863 

Does this have to do with the limited range of "int"? or is there something wrong with my code?

Here is the code:

using std::cout;

int main()
{

int n = 50, f1 = 0, f2 = 1, fn = 0, i = 0;

cout << "0 ";
for (i = 0; i < n; i++)
{
    fn = f1 + f2;
    f2 = f1;
    f1 = fn;

    cout << fn << " ";
}

Upvotes: 1

Views: 1168

Answers (3)

Jairo Flori&#225;n
Jairo Flori&#225;n

Reputation: 1

Try using "long int" instead of "int".

Upvotes: 0

I'll bet it does have something to do with the range of int. you're probably overflowing

An integer normally has 32 bits, and one of those bits is the sign, so if you have a number like

01111111111111111111111111111111

which is a little bit over 2 billion, and you add 2 to it, then you get

10000000000000000000000000000001

which is negative(the first number is the sign, 0 is positive and 1 is negative)

If you want to store more numbers, you can use long ints.

Upvotes: 2

IanPudney
IanPudney

Reputation: 6021

Yes, this has to do with the limited range of int. This is called rollover or overflow, and works just like the odometer in your car. Once the number passes its highest possible value, it rolls over to its lowest possible value (which for int is a negative number). Consider using an unsigned int or long unsigned int, though the second one is not neccessarily longer (it's platform-dependent). A long double can hold even bigger numbers. If you'd like to use an arbitrarily large number (as big as you want), you can find appropriate libraries in answers to this question.

Upvotes: 2

Related Questions