I'm working on altering my Fibonacci sequencer so that the numbers after reaching ~100th term don't wrap around and become negative. How do I use BigInteger in this code that I wrote:
我正在修改我的斐波那契数列,这样在~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();
}
}
I've searched google high and low and I can't find anything specific to my case.
我搜索了谷歌的高低,我找不到任何与我的情况有关的东西。
2 个解决方案
#1
4
If you are sure that you only want to use BigInteger then you should think of creating array of BigInteger. So like
如果您确定只想使用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])
See this add API
看到这个API添加
#2
1
If total is also BigInteger, then
如果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])`
#1
4
If you are sure that you only want to use BigInteger then you should think of creating array of BigInteger. So like
如果您确定只想使用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])
See this add API
看到这个API添加
#2
1
If total is also BigInteger, then
如果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])`