如何使用BigInteger与数组?

5

我正在修改我的斐波那契数列生成器,使其在达到约100项后,数字不会绕回并变为负数。请问在我编写的代码中如何使用BigInteger:

package me.kevinossia.mystuff;

import java.util.Scanner;

public class FibonacciDisplayer 
{
public static void main(String[] args)
{

    Scanner input = new Scanner(System.in);
    int total;
    System.out.print("This is a Fibonacci sequence displayer.\nHow many numbers would you like it to display?");
    total = input.nextInt();
    long[] series = new long[total];
    series[0]=0;
    series[1]=1;

    for(int i=2;i<total;i++)
    {
        series[i]=series[i-1] + series[i-2];
    }
    for(int j=0; j<total; j++)
    {
        System.out.print(series[j] + "\n");
    }
    input.close();
}
}

我在谷歌上搜索了很久,但是没有找到与我的情况特别相关的内容。


那么,使用 BigInteger 而不是 long - dmon
转到此链接。希望这可以帮助您:http://www.n-e-x.co.uk/dokuwiki/doku.php?id=code:java:fibonacci - Shailesh Saxena
我已经在Google上搜索了很多,但是没有找到适用于我的情况的具体资料。你搜索了什么?如果你搜索BigInteger,肯定会找到很多关于如何使用它的例子... - Stephen C
我做了,只是没有为斐波那契数列做任何事情。 - Kevin Ossia
2个回答

6
如果您确定只想使用BigInteger,则应考虑创建BigInteger数组。就像这样:
BigInteger[] series = new BigInteger[total];
series[0]=BigInteger.ZERO;
series[1]=BigInteger.ONE;

and in loop do
series[i] = series[i-1].add(series[i-2])

请查看这个add(加) API。


1
非常感谢,但是我不熟悉ZERO和ONE。我在Javadocs上看到了它们,但没有说明它们是什么,或者至少我没有看到。 - Kevin Ossia
2
@KevinOssia 如果您不熟悉此内容,简单地说BigInteger.valueOf(0L); 或 BigInteger.valueOf(1L)应该会给您相同的结果。 - Adrian Shum

1
如果total也是BigInteger,则:
BigInteger total = new BigInteger("1000000000000000");
BigInteger[] series = new BigInteger[total.intValue()];
series[0] = BigInteger.ZERO;
series[1] = BigInteger.ONE;
series[i] = series[i-1].add(series[i-2]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接