tags:

views:

338

answers:

5

Given Wikipedia's discussion of Double Factorials, can anyone suggest where I might find a bignum version of this for Perl, or else suggest how it might be written?

+3  A: 

Perl will handle whatever your C compiler can handle, for anything bigger you should be using Math::BigInt.

I would recommend you read perlnumber.

A definition for the double factorial (in perl golf):

sub f{$_[0]&&$_[0]>=2?$_[0]*f($_[0]-2):1}
dsm
I've been using BigInt. The issue is that BigInt doesn't have anything like a Double Factorial. It has `bfac` but that's a different beastie.
boost
I thought you were after a number big enough to store the result, not a math library that would provide the operation.
dsm
@boost: You can easily write one for you.
Hynek -Pichi- Vychodil
@H.P.Y. Not wanting to make life /too/ easy I did provide one ;)
dsm
Scalar value @_[0] is better written as $_[0] in stackoverflow.com/questions/416377. Golfing is fun, but golfing with warnings turned on is even better. ;)
pjf
@pjf - corrected
dsm
+1  A: 

If you're doing floating point calculations with (double) factorials, you can quickly get into overflow or underflow situations. It's usually best to work with logarithms. Adding and subtracting logarithms of factorials then taking the exponential at the end is more reliable than multiplying and dividing factorials directly. More details here.

John D. Cook
+1  A: 

Here are lots of alternative approaches to implementing Fast Factorial Functions. The Poor Man's algorithm may be a good choice for you, as it uses no Big-Integer library and can be easily implemented in any computer language and is even fast up to 10000!.

The translation into Perl is left as an exercise for the OP :-)

Kevin Haines
+2  A: 

Perl 5.8 and later come with the bignum package. Just use it your script and it takes care of the rest:

use bignum;

I talk about this a bit in Mastering Perl when I use the factorial in the "Profiling" chapter.

brian d foy
+1  A: 

Although dsm's answer is accurate, the real way to calculate factorials in Perl, regardless of whether you use dsm's algorithm (golfed or not) is to memoize it. If you are going to call it with any frequency, you'll want to memoize any recursive mathematical function.

use Memoize;
memoize( 'fact2' );

sub fact2 {$_[0]&&$_[0]>=2?$_[0]*fact2($_[0]-2):1}
Axeman
boost