Reputation: 7769
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?
Upvotes: 2
Views: 1615
Reputation: 29854
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}
Upvotes: 1
Reputation: 132859
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.
Upvotes: 1
Reputation: 2552
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 :-)
Upvotes: 2
Reputation: 10395
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}
Upvotes: 3