Possible Duplicate:
Calculate the factorial of an arbitrarily large number, showing all the digits
This question might be asked thousand times here. I am repeating my question with a modification. I want to calculate factorial of a large number (max range of the number=10^6
). Generally we uses a for
loop from i=1
to i=number
and every time multiplying the old value to the new value. This is fine for small numbers but what if i have a large number? The range of for
loop is increased now. Java primitive data type int
, long
can't handle the resultant large number. They simply overflows. Although i knew about BigInteger
class, which can handle this large output but still for
loop is not suiting better here for me. Can somebody please suggest me any tick, any hack to calculate factorial of a number? Below is the simple program which works fine for small number-
public long getFactorial(long number) {
long factorial = 1;
for (long i = 1; i <= number; ++i) {
factorial *= i;
}
return factorial;
}