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

Re: [FWP] Factorial Elegance



On Thu, Sep 14, 2000 at 10:19:38PM -0500, tayers@bridge.com wrote:
> 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];
>     }
>   }

Given the pace of growth of factorial, using a cache isn't that helpful.
If you need to do many factorials, you might as well pre calculate all
of them and save all the conditionals in your sub.

However, if you want a cute little function, that does factorials
giving exact answers, no matter how large the argument is:

  sub factorial {local $" = "*"; my @a = (1, 1 .. shift); `echo '@a' | bc`}

(Granted, it returns the wrong results for arguments < 0, but so does the
 above code.)


Abigail

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