How can I compute double factorials in Perl?
Asked Answered
Q

4

2

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?

Quartziferous answered 6/1, 2009 at 12:45 Comment(0)
P
3

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}
Pemberton answered 6/1, 2009 at 12:57 Comment(5)
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.Quartziferous
I thought you were after a number big enough to store the result, not a math library that would provide the operation.Pemberton
@boost: You can easily write one for you.Vidal
@H.P.Y. Not wanting to make life /too/ easy I did provide one ;)Pemberton
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. ;)Salespeople
C
2

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

Collusion answered 6/1, 2009 at 21:48 Comment(0)
F
1

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.

Foreknow answered 6/1, 2009 at 22:9 Comment(0)
E
1

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}
Eau answered 8/1, 2009 at 5:33 Comment(1)
probably you want to edit that to sub fact2 {$_[0]&&$_[0]>=2?$_[0]*fact2($_[0]-2):1}Quartziferous

© 2022 - 2024 — McMap. All rights reserved.