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();
}
}

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

4

2 回答 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])

请参阅此添加API

于 2013-03-21T03:46:27.553 回答
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]);
于 2015-03-04T06:32:12.910 回答