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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592
bugmagnet
  • 7,631
  • 8
  • 69
  • 131

4 Answers4

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}
dsm
  • 10,263
  • 1
  • 38
  • 72
  • 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. – bugmagnet Jan 06 '09 at 13:13
  • I thought you were after a number big enough to store the result, not a math library that would provide the operation. – dsm Jan 06 '09 at 13:34
  • @boost: You can easily write one for you. – Hynek -Pichi- Vychodil Jan 06 '09 at 13:54
  • @H.P.Y. Not wanting to make life /too/ easy I did provide one ;) – dsm Jan 06 '09 at 13:56
  • 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 Jan 06 '09 at 15:58
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 :-)

Kevin Haines
  • 2,492
  • 3
  • 18
  • 19
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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
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}
Axeman
  • 29,660
  • 2
  • 47
  • 102