问题
Data type to hold a very large number say 1000 or more digits? I need to find the factorial of a large number say 100000000. My factorial program works nice for a smaller number.
long factorial(int x)
{
long fact=1;
if(x<0)
{
System.out.println("Incorrect input, enter a positive number");
fact=0;
}
if(x==0)
fact=1;
if(x>0)
{
fact=x;
fact=fact*factorial(x-1);
}
return fact;
}
回答1:
You need a BigInteger
. It can hold an arbitrarily large number.
But in your case 100000000!
is such a huge number, that nothing can help.
回答2:
You should use a log of gamma function, since gamma(n) = (n-1)!
Far more efficient than your naive, student way of doing things. It'll be a double in that case, and the natural log will grow more slowly than the value does.
Recursion? Please. Your problem won't be the size of the value you pass back - you'll get too many stack frames and out of memory error long before that.
回答3:
While BigInteger
will theoretically handle such a value, you won't be able to compute it in practise.
First, your algorithm uses recursion, so you'd need 100.000.000 recursive calls of factorial
. You'll get stack overflow far before computing the result. You'd have to modify your algorithm to avoid recursion (use a loop for example).
Second, the result will be huge. Using formulas for approximating factorials such as
log n! ~~ n log(n/e)
we can conclude that your number will have more than 750.000.000 digits. While with some luck you might be able to fit it into your memory, you will certainly not be able to compute the number in any reasonable time. Just imagine - you'll have to perform 100.000.000 multiplications with numbers that have hundreds of millions of digits.
来源:https://stackoverflow.com/questions/17394221/what-data-type-can-be-used-to-hold-the-value-of-the-factorial-of-100-000-000