in reply to New Jersey Lottery Probability

Okay, I have succumb to my curiosity: Because this turned out to be a good example of our motto (TIMTOWTDI) ... I had to do a benchmark with all the possibilities
use strict; use Benchmark; timethese(1000000, { 'p1' => sub { p1( 50, 5) }, 'p2' => sub { p2( 50, 5) }, 'p3' => sub { p3( 50, 5) }, 'p4' => sub { p4( 50, 5) }, 'p5' => sub { p5( 50, 5) }, 'p6' => sub { p6( 50, 5) }, 'p7' => sub { p7( 50, 5) }, }); #chromatic sub p1 { my $probability = 1; my ($number, $times) = @_; while ($times-- > 0) { $probability *= $number; $number--; } return $probability; } #btrott sub p2 { my($number, $times, $prob) = (@_, 1); $prob *= $number-- while $times--; $prob; } #perlmonkey sub p3 { my $number = shift; my $count = shift || return 1; return $number * p3($number-1,$count-1); } #perlmonkey sub p4 { return $_[1] ? $_[0] * p4($_[0]-1,$_[1]-1) : 1; } #chromatic sub p5 { my ($prob, $start) = (1, shift); $prob *= $start-- foreach (1 .. $_[0]); $prob; } #chromatic sub p6 { my $prob = 1; $prob *= $_ foreach ((($_[0]+1) - $_[1]) .. $_[0]); return $prob; } #chromatic sub p7 { my $prob = 1; return (map { $prob *= $_ } (($_[0] - $_[1] + 1) .. $_[0]))[-1]; }
And the results:
Benchmark: timing 1000000 iterations of p1, p2, p3, p4, p5, p6, p7... p1: 61 wallclock secs (45.42 usr + 0.16 sys = 45.58 CPU) p2: 45 wallclock secs (35.92 usr + 0.11 sys = 36.03 CPU) p3: 127 wallclock secs (102.34 usr + 0.31 sys = 102.65 CPU) p4: 90 wallclock secs (71.84 usr + 0.31 sys = 72.15 CPU) p5: 58 wallclock secs (46.11 usr + 0.14 sys = 46.25 CPU) p6: 55 wallclock secs (43.51 usr + 0.15 sys = 43.66 CPU) p7: 85 wallclock secs (68.11 usr + 0.22 sys = 68.33 CPU)
And the winner is ... btrott with the slimmed down version from chromatic.
And the loser is... me as I suspected, recursion is slow.