I just peeked in Math::Big. The factorial implementation is very slow.

You should find a significant performance improvement with:

# # Usage: # factorial($n) = 1*2*...*$n # factorial($m, $n) = $m*($m+1)*...*$n # sub factorial { #divide and conquer unshift @_, 1 if 2 != @_; my ($m, $n) = @_; if ($m < $n) { my $k = int($m/2 + $n/2); return factorial($m, $k) * factorial($k+1, $n); } else { return Math::BigInt->new($m); } }
(Incremental improvements over that are easily achieved as well.)

I'll submit the suggestion to the maintainer.

UPDATE: I remember the overload interface being slower on old Perl's, but on my machine (5.8.0) it seems marginally faster. So I replaced:

return Math::BigInt->new(factorial($m, $k))->bmul(factorial($k+1,$ +n));
with
return factorial($m, $k) * factorial($k+1, $n);

UPDATE 2: Out of curiousity I wondered how the above Perl would compare with Ruby:

# # Usage: # factorial(n) = n*(n-1)*...*1 # factorial(n, m) = n*(n-1)*...*m def factorial (n, m=1) if m < n then k=(m+n)/2; factorial(k, m) * factorial(n, k+1); else m end end
This ran about 10x faster than Perl. Of course a naive factorial implementation in Ruby runs several times as fast as the smart one does in Perl.

The difference is mainly what we get for all of the layers of getting around variables autoconverting themselves inappropriately for large integers. If you want to work with large integers, Perl is not the language to do it with.


In reply to Re: Re: Hypergeometric Probability Calculation (speeding up 'choose' ) by tilly
in thread Hypergeometric Probability Calculation by Itatsumaki

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.