Number at f(93) in fibonacci series has negative value, how?

前端 未结 3 1791
别那么骄傲
别那么骄傲 2020-12-21 04:20

I am trying to printout fibonacci series upto \'N\' numbers. All works as per expectation till f(92) but when I am trying to get the value of f(93), values turns out in nega

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 04:53

    This happened because the long type overflowed. In other words: the number calculated is too big to be represented as a long, and because of the two's complement representation used for integer types, after an overflow occurs the value becomes negative. To have a better idea of what's happening, look at this code:

    System.out.println(Long.MAX_VALUE);
    => 9223372036854775807  // maximum long value
    System.out.println(Long.MAX_VALUE + 1);
    => -9223372036854775808 // oops, the value overflowed!
    

    The value of fibo(93) is 12200160415121876738, which clearly is greater than the maximum value that fits in a long.

    This is the way integers work in a computer program, after all they're limited and can not be infinite. A possible solution would be to use BigInteger to implement the method (instead of long), it's a class for representing arbitrary-precision integers in Java.

提交回复
热议问题