Java recursive method to find factorial returns negative output

Abdalnassir Ghzawi :

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));
}
}
Nicholas K :

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

Hope it helps!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=115189&siteId=1