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.


In reply to Factorial algorithm execution time by gri6507

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.