Hi fellow monks,
I don't remember why I even started doing this (probably as a passtime at work), but here are several algorithms to calculate the factorial of an integer (as in 6! = 6*5*4*3*2*1).
use Math::BigInt;
use Benchmark;
use strict;
$|++;
my $t0;
my $t1;
my $i = Math::BigInt->new($ARGV[0]);
$t0 = new Benchmark;
fact($i);
$t1 = new Benchmark;
print "Method 1: ",timestr(timediff($t1, $t0)),"\n";
$t0 = new Benchmark;
fact2($i,1);
$t1 = new Benchmark;
print "Method 2: ",timestr(timediff($t1, $t0)),"\n";
$t0 = new Benchmark;
fact3($i);
$t1 = new Benchmark;
print "Method 3: ",timestr(timediff($t1, $t0)),"\n";
sub fact{
my $n = Math::BigInt->new(shift);
return 1 unless $n->bcmp(0);
return $n->bmul(fact($n->bsub(1)));
}
sub fact2{
#Tail Recursion Ellimination
my $n = Math::BigInt->new(shift);
my $f = shift;
if (!$n->bcmp(0)) {return $f}
else {return &fact2($n->bsub(1),$n->bmul($f))}
}
sub fact3{
#no recursion at all
my $n = Math::BigInt->new($_[0]);
my $i = $_[0]-1;
while($i){
$n = Math::BigInt->new($n->bmul($i--));
}
return $n;
}
What really surprised me was that the recursive algorithm is faster than the straight up loop. Why is that? Isn't it true that in the recursive function, extra steps are taken to store the intermediate values in a stack? Is this to imply that recursion is faster than a loop?? Thanks for your wisdom.
P.S. Suggestions for more robust algorithms are welcome.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.