我正在研究一个找到Fibonacci数的程序。第一个版本的作业要求返回长数据类型,现在我们必须更改函数以返回BigInteger。我不知道如何更改我的函数以发回BigInteger类型。这是我有的:
public static BigInteger fibonacci_Loop(int f) {
BigInteger previous, current;
for(int i = 0; i < f; i ++) {
BigInteger sum = previous.add(current);
previous = current;
current = sum;
}
return previous;
}
它不会运行,因为它要我初始化之前和当前,任何时候我这样做都不会返回正确的数字。我不完全确定如何使用BigInteger,任何建议将不胜感激。
下面的代码适合我。初始化为零,当前为1并同样运行循环。请注意,循环运行比所需的fibnacci索引少一个。
public static BigInteger fibonacci_Loop(int f) {
BigInteger previous = BigInteger.ZERO;
BigInteger current = BigInteger.ONE;
for(int i = 0; i < f-1; i ++) {
BigInteger sum = previous.add(current);
previous = current;
current = sum;
}
return previous;
}
您可以使用带有String的构造函数:
BigInteger i = new BigInteger(“0”);
但是有一些常量,你可以使用:
BigInteger previous = BigInteger.ZERO;
BigInteger current= BigInteger.ONE;
当您使用long时,它们是原始类型或盒装类型,因此在声明时它们默认为0。
但是,java.math.BigInteger是一个Object,因此您必须在使用它之前对其进行初始化。
将此行BigInteger previous, current;
更改为BigInteger previous = new BigInteger("0"), current = new BigInteger("1");
应该修复它。
规则:首先,您需要在对函数执行任何操作之前初始化函数内部声明的任何变量。
更改我们的函数以返回BigInteger
如果您只需要返回BigInteger,那么应该只使用long更改前一个函数的return语句
return new BigInteger(previous);