斐波那契值数组;高索引的值将数组值转换为负值



我创建了一个名为数字的数组,它将存储斐波那契序列的值。1、2、3、5等。问题是,当我试图调用索引值非常高的数组值时,数组值会变为负数。

numbers[10] = 144 

这是合理的,但

numbers[9999998] = -1448735941

有什么帮助吗?

public static void main(String[] args) {
    int[] numbers = new int[10000000];
    numbers[0] = 1;
    numbers[1] = 2;
    for(int x = 2; x<=numbers.length-1; x++)
    {
        numbers[x] = numbers[x-1] + numbers[x-2];
    }
    System.out.println(numbers[9999998]);
    System.out.println(numbers[10]);

溢出。一旦该值超过32位int的最大"容量",结果将环绕并从最小值(负数)开始。

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

long和BigInteger能够存储比int更高的值。

您遇到整数溢出。查看BigInteger以获得一个解决方法。

最新更新