I've been using this factorial program for Java:
public static long factorial(int a) {
if(a<1) {
return 1;
}
long result=1;
long x=a;
while(x>1) {
result*=x;
x--;
}
return result;
}
However, it seems to "break" and return a negative number after the factorial of 25. It returns a negative number for a while then just returns "0."
Am I doing anything wrong that is causing this?
You've overflowed long
.
Use BigInteger
instead.
25! = 15511210043330985984000000
The maximum value of a long in Java is 2^63-1 = 9223372036854775807
(source).
25! is about 1.7*10^6 the size of the largest value a long can store in Java. Use a BigInteger
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With