【问题标题】:Getting NULL when calling recursive method using BigIntegers and memoization使用 BigIntegers 和 memoization 调用递归方法时获取 NULL
【发布时间】: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


    【解决方案1】:

    你假设一个 BigInteger 数组像一个长数组一样以零填充,但它以空值开始,因为它是一个对象数组,所以这样:

    if(fval[index] != BigInteger.ZERO){
        result=fval[index];
    }
    

    将始终返回 null,因为 null 的值不等于 BigInteger.ZERO

    如果你添加这个:

    for (int i = 0; i < index+1; i++) {
      fval[i] = BigInteger.ZERO;
    }
    

    在您致电 fib_rec 之前,它会起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 1970-01-01
      • 2014-03-02
      相关资源
      最近更新 更多