Why does my recursion program print a negative number?

My code for whatever reason is printing out a negative number when i run it with certain numbers(17). It is supposed to find the factorial of a number and print it out however clearly that isn't happening.

package recursion;

public class recursion_1 {

public static void main(String[] args) {
int x = factorial(17);
System.out.println(x);
}
public static int factorial(int N) { 
       if (N == 1) return 1; 
       return N * factorial(N-1); 
    }   
}
Jon Skeet
people
quotationmark

You're encountering integer overflow.

factorial(17) is 3.5568743e+14, which is well beyond the bounds of int. When an integer operation overflows, it can end up negative. For example:

int x = Integer.MAX_VALUE;
x++;
System.out.println(x); // Very large negative number

In your case, you'll have overflowed several times - even if the result were positive, it still wouldn't be right.

If you need integers in the range of [-263, 263-1] you can use long instead of int. If you want arbitrarily large integers, use BigInteger instead. For example:

// Note rename of parameter to follow Java conventions
public static BigInteger factorial(int n) {
    return factorial(BigInteger.valueOf(n));
}

public static BigInteger factorial(BigInteger n) {
    if (n.equals(BigInteger.ONE)) {
        return BigInteger.ONE;
    }
    return n.multiply(n.subtract(BigInteger.ONE));
}

people

See more on this question at Stackoverflow