[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] Factorial Elegance



My department gives a short Perl test as part of the interview
process. A new version was presented yesterday so I thought I'd take
it for fun. One of the questions was to write a function to return
x-factorial given x.

I jotted down the following (with a little tweaking afterward). It's
not tricky or obfuscated and it even works with 'use strict;' ;-), but
I think it's a nifty, efficient implementation due to a several
conveniences Perl provides.  

  {
    my @cache = (1);
    sub factorial {
      my $x = shift;
      return undef if $x < 0;
      unless (defined $cache[$x]) {
        my $p = $cache[$#cache];
        $cache[$_] = $p *= $_ for ($#cache+1..$x);
      }
      return $cache[$x];
    }
  }

BTW, if you change 

        $cache[$_] = $p *= $_ for ($#cache+1..$x);
to
        $cache[$_] = $cache[$_-1] * $_ for ($#cache+1..$x);

It runs about 25% slower on my computer. Is that due only to the extra
array lookup or something else? Thx.

Hope you have a very nice day, :-)
Tim Ayers (tayers@bridge.com)

P.S. Maybe I should have sent this to thanks@perl.org instead. :-)
After about three years of using the language, I'm still having a lot
of fun learning and am amazed just about everyday at what an
astounding language it is.



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe