小编典典

Java递归方法查找阶乘返回负输出[

algorithm

我知道这是溢出,但问题是20相对较小,这不应该发生吗?有没有更好的方法来找到大数(例如1000)的阶乘,而没有得到这个奇怪的结果?

public class RecursiveFunctionsExamples {

public int factorial(Integer n)
{
    Integer res;
    if(n == 0){ 
        res = 1;
    }else{
       res =  n * factorial(n-1);
    }

    return res;
}


public static void main(String[] args) {
    System.out.println(new RecursiveFunctionsExamples().factorial(20));
}
}

阅读 449

收藏
2020-07-28

共1个答案

小编典典

我知道这被标记为重复,但是使用来解决它recursionBigInteger只是请您(@Abdalnassir Ghzawi)要求它。

public BigInteger factorial(BigInteger n) {
    BigInteger res;
    if (n == BigInteger.ZERO) {
        res = BigInteger.ONE;
    } else {
        res = n.multiply(factorial(n.subtract(BigInteger.ONE)));
    }

    return res;
}

您需要使用来调用它:

System.out.println(new RecursiveFunctionsExamples().factorial(new BigInteger("6")));

希望能帮助到你!

2020-07-28