int
is finite
Your problem is the 32bit integer limit.
Java's int
datatype represents a signed 32bit integer meaning it can store values from -2^31 to 2^31-1 (2 147 483 647)
13! is 6 227 020 800 which is higher than that so it doesn't fit in an int
.
long
is bigger than int
but still finite
In order to fix this, you can use long
which represents a signed 64bit integer:
public static long factorial(long n) {
for(int i=(int)n-1;i>=1;i--){
n=n*i;
}
return n;
}
long
allows ranges from -2^63 up to 2^63-1 (a number with 18 digits) which allows factorials until 20!
.
Get real big with BigInteger
If you want to. go even further, you can use BigInteger
:
public static BigInteger factorial(long n) {
BigInteger value=BigInteger.valueOf(n);
for(int i=n-1;i>=1;i--){
value=value.multiply(BigInteger.valueOf(i));
}
return value;
}
While BigInteger
also isn't infinite (ranging from -2^(2^32)
until to -2^(2^32)
at minimum), it should be sufficient for your purpose. This is explained in the Javadoc of BigInteger
:
BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive)