There are a couple of changes. First, there is no need to multiply by 1. The answer is not going to change :-). Second, you are correct in saying that it's best to multiply the smallest number by the largest first. So, in this case, the left over "4" from the first step should be the first number in the second step. These are implemented in fact8(). If you run it, you'll see that it run's just abit faster.2 * 3 * 4 * 5 * 6 = | | | | | +-------+ | +---------------+ 4 * 12 * 15 = | | +---------+ 12 * 60 = 120
sub fact8{ #divide and conquer without recursion my @N = (2 .. shift); my @M; my $tmp; while ($#N){ while(@N){ $tmp = pop(@N); if (($_ = shift(@N))){push(@M,Math::BigInt->new($tmp)->bmul($_)) +} else {unshift(@M,$tmp)} } while(@M){ $tmp = pop(@M); if (($_ = shift(@M))){push(@N,Math::BigInt->new($tmp)->bmul($_)) +} else {unshift(@N,$tmp)} } } return @N; } perl fact.pl 5000 Method 8 (new func): 28 wallclock secs (28.65 usr + 0.00 sys = 28.65 +CPU) Method 7 (your func): 30 wallclock secs (29.06 usr + 0.00 sys = 29.06 + CPU)
In reply to Re: Re: Factorial algorithm execution time
by gri6507
in thread Factorial algorithm execution time
by gri6507
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |