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]; }