I'd only ever used Eratosthenes' Sieve to find a list of all primes up to a limit and, stupidly, assumed that it would be equally good at testing whether a single number was prime. Silly me!
You have shown your method to be much faster but there's still room for improvement. You reject all even numbers the first time through your loop so there's no point in using even numbers again as divisor. Instead, take the evens test out of the loop then employ a C-style loop to test only odd divisors.
The code. I've tweaked things to return 0 if not prime in order to make testing easier.
use strict;
use warnings;
use 5.010;
use Benchmark qw{ cmpthese };
use Test::More qw{ no_plan };
my %methods = (
eratosthenes => sub
{
my $toTest = shift;
my $sqrtLimit = sqrt $toTest;
my $sieve = q{};
vec( $sieve, 0 , 1 ) = 1;
vec( $sieve, 1 , 1 ) = 1;
vec( $sieve, $toTest, 1 ) = 0;
my $marker = 1;
while ( $marker < $sqrtLimit )
{
my $possPrime = $marker + 1;
$possPrime ++ while vec( $sieve, $possPrime, 1 );
my $fill = 2 * $possPrime;
while ( $fill <= $toTest )
{
vec( $sieve, $fill, 1 ) = 1;
$fill += $possPrime;
}
last if vec( $sieve, $toTest, 1 );
$marker = $possPrime;
}
return not vec( $sieve, $toTest, 1 );
},
tobyink => sub
{
my $num = shift;
return 0 if $num == 1; # 1 is not prime
for my $div (2 .. sqrt $num)
{
return 0 if $num % $div == 0;
}
return 1;
},
tobyinkPlus => sub
{
my $toTest = shift;
return 0 if $toTest == 1;
return 1 if $toTest == 2;
return 0 unless $toTest % 2;
my $sqrtLimit = sqrt $toTest;
for ( my $div = 3; $div <= $sqrtLimit; $div += 2 )
{
return 0 unless $toTest % $div;
}
return 1;
},
);
say qq{Testing with value 2 which is a prime};
foreach my $method ( sort keys %methods )
{
ok(
$methods{ $method }->( 2 ) == 1,
qq{$method}
);
}
say qq{Testing with value 8357 which is not a prime};
foreach my $method ( sort keys %methods )
{
ok(
$methods{ $method }->( 8357 ) == 0,
qq{$method}
);
}
say qq{Testing with value 9293 which is a prime};
foreach my $method ( sort keys %methods )
{
ok(
$methods{ $method }->( 9293 ) == 1,
qq{$method}
);
}
my @testValues;
push @testValues, int rand 1e6 for 1 .. 20;
cmpthese(
-20,
{
map
{
my $codeStr =
q[sub { my $isPrime = $methods{ ] .
$_ .
q[ }->( $_ ) for @testValues; }];
$_ => eval $codeStr;
}
keys %methods
}
);
The benchmark results.
Testing with value 2 which is a prime
ok 1 - eratosthenes
ok 2 - tobyink
ok 3 - tobyinkPlus
Testing with value 8357 which is not a prime
ok 4 - eratosthenes
ok 5 - tobyink
ok 6 - tobyinkPlus
Testing with value 9293 which is a prime
ok 7 - eratosthenes
ok 8 - tobyink
ok 9 - tobyinkPlus
Rate eratosthenes tobyink tobyinkPlus
eratosthenes 0.154/s -- -100% -100%
tobyink 1291/s 838266% -- -35%
tobyinkPlus 1984/s 1288047% 54% --
1..9
I hope this is of interest.