The number in f (93) in the Fibonacci series has a negative value, how?

I am trying to print a Fibonacci series with the numbers "N". Everything works in anticipation until f (92), but when I try to get the value of f (93), the values ​​turn out to be negative: "-6246583658587674878". How is this possible? What is the logic error below?

public long fibo(int x){
    long[] arr = new long[x+1];
    arr[0]=0;
    arr[1]=1;
    for (int i=2; i<=x; i++){
        arr[i]=arr[i-2]+arr[i-1];
    }
    return arr[x];
}

f(91) = 4660046610375530309
f(92) = 7540113804746346429    
f(93) = -6246583658587674878

Is it because of the data type? What other data type should I use to print a Fibonacci series with N numbers? N can be any integer within the range [0,10,000,000].

+4
source share
2 answers

You are faced with integer overflow:

 4660046610375530309 <-- term 91
+7540113804746346429 <-- term 92
====================
12200160415121876738 <-- term 93: the sum of the previous two terms
 9223372036854775808 <-- maximum value a long can store

, BigInteger, .
BigDecimal:

public String fibo(int x){
    BigInteger[] arr = new BigInteger[x+1];
    arr[0]=BigInteger.ZERO;
    arr[1]=BigInteger.ONE;
    for (int i=2; i<=x; i++){
        arr[i]=arr[i-2].add(arr[i-1]);
    }
    return arr[x].toString();u
}

, String ( BigInteger), 93 x , java- .

+5

, long . : , long, - , , . , , :

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

fibo(93) 12200160415121876738, , long.

, , . BigInteger ( long), Java.

+4

Source: https://habr.com/ru/post/1526086/


All Articles