将函数从返回 long 更改为 BigInteger

Changing function from returning long to BigInteger

我正在开发一个查找斐波那契数列的程序。作业的第一个版本要求将 long 数据类型 returned,现在我们必须将函数更改为 return 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;
}

它不会 运行 因为它要我初始化以前的和当前的而且我每次这样做都不会 return 正确的数字。我不完全确定如何使用 BigInteger,如有任何建议,我们将不胜感激。

下面的代码适合我。将 previous 初始化为零,将 current 初始化为 1,同样 运行 循环。请注意,循环 运行 比所需的斐波那契指数小一。

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;

}

当您使用 long 时,它们要么是原始类型,要么是盒装类型,因此在声明时它们默认为 0。

java.math.BigInteger 然而是一个对象,所以你必须在使用它之前初始化它。

将此行 BigInteger previous, current; 更改为 BigInteger previous = new BigInteger("0"), current = new BigInteger("1"); 应该可以解决问题。

您可以使用接受字符串的构造函数:

BigInteger i = new BigInteger(“0”);

但是您可以使用常量:

BigInteger previous = BigInteger.ZERO;
BigInteger current= BigInteger.ONE;

规则 : 首先你需要在对函数执行任何操作之前初始化在函数内部声明的任何变量。

change our function to return BigInteger

如果你只需要 return BigInteger 那么应该只将你之前函数的 return 语句更改为

return new BigInteger(previous);