如何将BigInteger与数组一起使用?

时间:2013-03-21 03:39:17

标签: java arrays biginteger fibonacci

我正在努力改变我的Fibonacci音序器,以便在达到~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();
}
}

我搜索谷歌的高低,我找不到任何特定于我的案例。

2 个答案:

答案 0 :(得分:5)

如果您确定只想使用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 :(得分: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]);