Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factorial of 170+

Tags:

php

factorial

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);
}
like image 840
Tom Avatar asked Nov 22 '10 20:11

Tom


People also ask

How many digits is 170 factorial?

- Factorial of 170. 170 factorial has 307 digits.

What is the factorial of 171?

- Factorial of 171. 171 factorial has 310 digits.


6 Answers

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

like image 172
EboMike Avatar answered Oct 06 '22 01:10

EboMike


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.

like image 25
Crozin Avatar answered Oct 05 '22 23:10

Crozin


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

like image 28
jon_darkstar Avatar answered Oct 05 '22 23:10

jon_darkstar


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.

like image 44
GWW Avatar answered Oct 05 '22 23:10

GWW


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/

like image 29
abscondment Avatar answered Oct 06 '22 00:10

abscondment


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.

like image 39
thelem Avatar answered Oct 06 '22 00:10

thelem