Java递归方法找到阶乘返回负输出 [英] Java recursive method to find factorial returns negative output

查看:120
本文介绍了Java递归方法找到阶乘返回负输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它是溢出但是20是相对较小的数字这不应该发生吗?有没有更好的方法来找到像1000这样的大数的阶乘而没有得到这个奇怪的结果?

I know it is overflow but the thing is 20 is relatively small number this should not happen right? is there a better approach to find factorial of large numbers such as 1000 with out getting this bizarre result?

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));
}
}


推荐答案

我知道这是标记重复,但使用递归 BigInteger 解决它只是因为你(@Abdalnassir Ghzawi)要求它。

I know this is marked duplicate, but solving it using recursion and BigInteger just coz you (@Abdalnassir Ghzawi) requested for it.

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;
}

您需要使用以下方式调用它:

You'll need to call it using :

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

希望有所帮助!

这篇关于Java递归方法找到阶乘返回负输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆