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

Re: [FWP] Factorial Elegance



>>>>> "R" == Rick Klement <rklement@pacbell.net> writes:
R> sub xxx { eval join '*', 1 .. shift }

>>>>> "M" == Michael G Schwern <schwern@pobox.com> writes:
M> Oh, much too much code.
M> use Tie::Math qw(f X);
M> tie %factorial, 'Tie::Math', sub { f(X) = X * f(X-1) },
M>                              sub { f(0) = 0;  f(1) = 1; };

Well, the main reason I post to this list is to learn. The secondary
reason is to have my ego smashed. :-}

Rick's solution is excellently perlish. 

I benchmarked calculating 170!. I did it with and without caching,
i.e. in Michael's and my solution I reset the cache before calling
factorial(170). I'm really impressed at the speed of Michael's
solution. How in the world is it so fast?

Without caching:
  Benchmark: timing 7000 iterations of klement, schwern, tayers...
     klement: 36 wallclock secs (23.38 usr +  0.11 sys = 23.49 CPU) @ 298.00/s (n=7000)
     schwern:  1 wallclock secs ( 0.56 usr +  0.00 sys =  0.56 CPU) @ 12500.00/s (n=7000)
      tayers:  6 wallclock secs ( 3.60 usr +  0.01 sys =  3.61 CPU) @ 1939.06/s (n=7000)

With caching:
  Benchmark: timing 7000 iterations of klement, schwern, tayers...
     klement: 36 wallclock secs (23.76 usr +  0.09 sys = 23.85 CPU) @ 293.50/s (n=7000)
     schwern:  1 wallclock secs ( 0.51 usr +  0.00 sys =  0.51 CPU) @ 13725.49/s (n=7000)
      tayers:  5 wallclock secs ( 3.49 usr +  0.00 sys =  3.49 CPU) @ 2005.73/s (n=7000)

So as always, my solution is mediocre, but my initial reaction to
Michael's answer was, "If I wanted to write code like that, I'd learn
Prolog." ;-)

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

P.S. Is it self-centered to consider myself the pet Llama of FWP? :-)


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