Calculate 100 factorials with all numbers

I ran into the problem of calculating 100 factorials.

Here is what I tried first in Perl to calculate 100! :

#!/usr/bin/perl use strict; use warnings; use Math::BigInt; my $n=<>; chomp($n); print fac($n); sub fac { my ($m) = @_; return 1 if($m <=1 ); return $m*fac($m-1); } 

But that gives me 9.33262154439441e+157 .

I need an answer with all the numbers.

What should I do?

+7
source share
3 answers

Parties (which most Perls use) have only ~ 16 digits of precision. You need to use a different system to get the required 158 digits of accuracy.

 use bigint; 

This will force Perl to automatically process all numbers in the script as Math::BigInt .

If you need more subtle control (to handle some numbers like BigInt and some numbers like floating point), then see Krishnachandra Sharma's solution and use the Math::BigInt constructor Math::BigInt .

Math::BigInt has a built-in factorial function, by the way:

 $ perl -MMath::BigInt -e 'print Math::BigInt->bfac(100)' 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 
+12
source

Parties (which most Perls use) have only ~ 16 digits of precision. You need another system to get the required 158 digits of accuracy. Try using Math::BigInt .

Here is the code.

 #!/usr/bin/perl use strict; use warnings; use Math::BigInt; my $n=100; Math::BigInt->new($n); print fac($n); sub fac { my ($m) = @_; return 1 if($m <=1 ); return Math::BigInt->new($m*fac($m-1)); } 

Produces 9332621544394415268169923e266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

+6
source

By definition, bigint works by overloading literal processing with integers and floating point, converting them to Math :: BigInt objects. Thus, using a simple for loop, we can get a factorial of very large integers.

 use bigint; my $fact = 1; for my $n (1..100) { $fact *= $n; } print "Factorial: \n", $fact , "\n"; 

This gives the following result:

 Factorial: 933262154439441526816992388562667004907159682643816214685929638952175 99993229915608941463976156518286253697920827223758251185210916864000000000000000 000000000 

whereas a regular program like this would tremble without a meaningful exit

 use integer; my $fact = 1; for my $n (1..100) { $fact *= $n; } print "Factorial: \n", $fact , "\n"; 

Output:

 Factorial: 0 
0
source

All Articles