The recursive algorithm multiplies smallest to largest, so most of the multiplications take place with the smallest number. The iterative algorithm multiplies largest to smallest so you are multiplying against a very, very big number a lot. Try this iterative implementation that mimics the order of operations in the recursive solution and see if it isn't faster:
sub fact4{
#no recursion at all
my $n = Math::BigInt->new(1);
foreach my $i (map Math::BigInt->new($_), 1..shift) {
$n = Math::BigInt->new($i->bmul($n));
}
return $n;
}
Also the order of the terms seems to matter. This version is not quite as fast:
sub fact5{
#no recursion at all
my $n = Math::BigInt->new(1);
foreach my $i (1..shift) {
$n = Math::BigInt->new($n->bmul($i));
}
return $n;
}
And since most of the time is spent dealing with multiplying big numbers, perhaps you want to divide fewer big numbers? The following is much faster than any other approach given because it limits multiplications with big numbers, but you have to pass it the raw number because Math::BigInt objects do not play well with the averaging manipulation it does:
sub fact6{
#divide and conquer
my $m = shift;
my $n = @_ ? shift : $m;
if ($m < $n) {
my $k = int($m/2 + $n/2);
return Math::BigInt->new(fact6($m, $k))->bmul(fact6($k+1,$n));
}
else {
return Math::BigInt->new($m);
}
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.