【发布时间】:2018-02-17 15:20:45
【问题描述】:
我得到了使用 long 数据类型的方法,但是当我调用我的 BigInteger 递归方法时,它在我 println 时显示为“null”。 这是适用于我的长递归方法:
public static long fib_rec(int n){
long result=1;
if(n<=2){
return result;
}
else{
if(fval[n]!=0){
result=fval[n];
}
else{
result = fib_rec(n-1) + fib_rec(n-2);
fval[n] = result;
}
return result;
}
}
同样,在我超过 n = 94 之前,该方法非常有效,其中的值对于长数据类型来说太大了。 这是我的 BigInteger 尝试,完整程序:
public class BigInt {
static BigInteger[] fval;
public static void main(String[] args) {
int index;
Scanner input = new Scanner(System.in);
index = input.nextInt();
fval = new BigInteger[index + 1];
System.out.println(fib_rec(index));
}
public static BigInteger fib_rec(int index){
BigInteger result = BigInteger.ONE;
if(index <= 2){
return result;
}
else{
if(fval[index] != BigInteger.ZERO){
result=fval[index];
}
else{
result = fib_rec(index-1).add(fib_rec(index-2));
fval[index] = result;
}
return result;
}
}
}
这返回 null,我不知道为什么......
【问题讨论】:
标签: java recursion biginteger memoization