Hello Lady_Aleena,
You are correct, and by eliminating even numbers up front, along with multiples of five, choroba’s solution can be speeded up by around a third:
#! perl use strict; use warnings; use Benchmark 'cmpthese'; use Test::More tests => 1; use constant MAX => 1e4; sub primes_choroba { my $n = shift; return if $n < 2; my @primes = (2); for my $i (3 .. $n) { my $sqrt = sqrt $i; my $notprime; for my $p (@primes) { last if $p > $sqrt; $notprime = 1, last if 0 == $i % $p; } push @primes, $i unless $notprime; } return @primes } sub primes_eliminate { my $n = shift; return if $n < 2; my @primes = (2, 3, 5); for (my $i = 7; $i <= $n; $i += 2) { next if 0 == $i % 5; my $sqrt = sqrt $i; my $notprime; for my $p (@primes) { last if $p > $sqrt; $notprime = 1, last if 0 == $i % $p; } push @primes, $i unless $notprime; } return @primes } is_deeply ( [ primes_choroba (MAX) ], [ primes_eliminate(MAX) ], 'same' ); cmpthese ( -10, { choroba => 'primes_choroba (MAX)', eliminate => 'primes_eliminate(MAX)', } );
Output:
17:20 >perl 1208_SoPW.pl 1..1 ok 1 - same Rate choroba eliminate choroba 64.3/s -- -26% eliminate 86.6/s 35% -- 17:20 >
But note that choroba’s solution is well over a hundred times faster than the non-sieve method you posted, so maybe an additional speedup of around 35% was irrelevant to the point he was making. :-)
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
In reply to Re^10: Number functions.. primes (ugly code runs faster)
by Athanasius
in thread Number functions I have lying around
by Lady_Aleena
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |