in reply to Factorial algorithm execution time
Also the order of the terms seems to matter. This version is not quite as fast:sub fact4{ #no recursion at all my $n = Math::BigInt->new(1); foreach my $i (map Math::BigInt->new($_), 1..shift) { $n = Math::BigInt->new($i->bmul($n)); } return $n; }
And since most of the time is spent dealing with multiplying big numbers, perhaps you want to divide fewer big numbers? The following is much faster than any other approach given because it limits multiplications with big numbers, but you have to pass it the raw number because Math::BigInt objects do not play well with the averaging manipulation it does:sub fact5{ #no recursion at all my $n = Math::BigInt->new(1); foreach my $i (1..shift) { $n = Math::BigInt->new($n->bmul($i)); } return $n; }
sub fact6{ #divide and conquer my $m = shift; my $n = @_ ? shift : $m; if ($m < $n) { my $k = int($m/2 + $n/2); return Math::BigInt->new(fact6($m, $k))->bmul(fact6($k+1,$n)); } else { return Math::BigInt->new($m); } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Factorial algorithm execution time
by gri6507 (Deacon) on Oct 18, 2002 at 14:05 UTC | |
by Anonymous Monk on Oct 18, 2002 at 23:29 UTC | |
by Aristotle (Chancellor) on Oct 19, 2002 at 01:32 UTC | |
by Anonymous Monk on Oct 19, 2002 at 03:06 UTC | |
by Aristotle (Chancellor) on Oct 19, 2002 at 11:24 UTC | |
| |
by Aristotle (Chancellor) on Oct 18, 2002 at 14:44 UTC | |
by gri6507 (Deacon) on Oct 18, 2002 at 16:42 UTC |