问题
everytime I try to get the factorial of 171, I get INF. 170 works fine. Is it possible to get the factorial of 171+ in a script? How? My function:
function factorial($n) {
if ($n == 0) return 1;
return $n * factorial($n - 1);
}
回答1:
You'll have to use BC Math or GNU MP extension. PHP doesn't provide any tools for high-values or high-precision operations OOTB.
回答2:
If you deal with very large numbers, you'll need to use an extension that allows you to do that.
There's BCMath ( http://www.php.net/manual/en/book.bc.php) , and GMP ( http://www.php.net/manual/en/book.gmp.php ).
回答3:
echo "1241018070217667823424840524103103992616605577501693185388951803611996075221691752992751978120487585576464959501670387052809889858690710767331242032218484364310473577889968548278290754541561964852153468318044293239598173696899657235903947616152278558180061176365108428800000000000000000000000000000000000000000"
really though, your function is fine. I think PHP lacks that kind of precision. I got the value (it is correct btw) in python
回答4:
You are probably getting a value that exceeds the maximum double precision float in a 32-bit machine (~10^308
). 170! factorial is ~7.25741562 × 10^307
which is just under that, however, 171! is larger. Your best bet is to use one of the libraries EboMike or Crozin recommends in their answers.
回答5:
It's a bigger number than you can hold using 32-bits. If you run the same code on a 64-bit computer then it should work.
回答6:
For large n, you can compute n! very quickly with little error using Stirling's approximation. Take a look at this post; it has an analysis of the function and some sample code:
http://threebrothers.org/brendan/blog/stirlings-approximation-formula-clojure/
来源:https://stackoverflow.com/questions/4249677/factorial-of-170