I have some method to find a factorial of big numbers. Could somebody explain, what's wrong with it and why i haven't any output?
public static long factorial(long num) {
BigInteger numm = BigInteger.valueOf(num);
BigInteger fact= BigInteger.valueOf(1);
for (; numm.compareTo(BigInteger.ZERO)==1 ; fact = fact.multiply(numm)) {
numm.subtract(BigInteger.ONE);
}
return fact.longValue();
}
You don't assign the subtraction value to numm
. This is the problem.
To stay with your code, use num + 1
because last part of the for loop execute after the substraction made. So, need one extra iteration.
Check that:
long num=5;
BigInteger numm = BigInteger.valueOf(num + 1);
BigInteger fact= BigInteger.valueOf(1);
for (; numm.compareTo(BigInteger.ONE)==1 ; fact = fact.multiply(numm)) {
numm = numm.subtract(BigInteger.ONE);
}
System.out.println(fact.longValue());