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.
In reply to Factorial algorithm execution time by gri6507
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |