且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Factorial java返回0

更新时间:2023-12-03 14:28:40

34的阶乘是关于3 * 10 38 - 它不适合 int ,它可以容纳最多2 * 10 9 的数字。价值34!即使在 long 中也不适合。

The factorial of 34 is about 3*1038 - it does not fit into an int, which could hold numbers up to 2*109. The value of 34! would not fit even in a long.

如果您需要计算如此大数的阶乘,请使用 BigInteger 类而不是。该类的对象可以保存任意大小的整数值。请注意,操作不会使用中缀运算符,但使用方法:

If you need to calculate factorials of such large numbers, use BigInteger class instead. Objects of that class can hold integer values of arbitrary size. Note that the operations would not be done with the infix operators, but with methods:

public BigInteger factorial (int numero ){
    if (numero < 0) {
        return BigInteger.ZERO;
    } else if (numero==0){
        return BigInteger.ONE;
    } else {
        return BigInteger.valueOf(numero).multiply(factorial(numero-1));
    }
}