BigInteger因子表1-30

时间:2016-03-31 02:38:40

标签: java biginteger factorial

我应该打印一个0到30之间的整数表以及它们的阶乘。我试过,但是我一直收到错误,说BigInteger(长)在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);
}

1 个答案:

答案 0 :(得分:1)

有一个BigInteger构造函数使用long,但它是private所以只能从BigInteger类本身调用。

您需要改为使用BigInteger.valueOf(n)