开发者

Factorial of 170+

开发者 https://www.devze.com 2023-01-26 03:55 出处:网络
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?

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);
}


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 ).


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.


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


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.


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/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消