BigInteger 阶乘 Table 1-30

BigInteger Factorial Table 1-30

我应该打印一个 table 从 0 到 30 的整数及其阶乘。我试过了,但我一直收到一条错误消息,提示 BigInteger(long) 在 BigInteger 中具有私有访问权限?想法?

public static void main(String[] args) {
    int x = 0;
    for (x = 0; x < 31;) {
        System.out.println(x + " " + factorial(x));

        x = x + 1;

    }
}

/*
       public static int factorial (int n) {   
       if (n == 0) {
             return 1;
        } else {
            return n * factorial (n-1);
           }
        }
         // error occuring at 13! could be because the number becomes too great for int to handle, resulting in an overflow error.

     }*/
public static BigInteger factorial(int n) {
    if (n == 0) {
        return BigInteger.ONE;
    } else {

        BigInteger result = new BigInteger(n).multiply(factorial(n - 1));(error here)

        return result;
    }
    //return new BigInteger(n) * factorial(n - 1);
}

有一个 BigInteger 构造函数采用 long,但它是 private,因此只能从 BigInteger class 本身调用。

您需要改用 BigInteger.valueOf(n)