in reply to
Re: a close prime number

in thread a close prime number

The speed of the is_prime function can be increase by about 140% by using the 2 4 trick used below.

`sub is_prime {
my %prime = map { $_ => 1 } (2, 3, 5, 7);
my %not_prime;
return sub {
my $n = shift;
return 1 if $prime{ $n };
return 0 if $n % 2 == 0 || $n % 3 == 0
|| exists $not_prime{ $n };
my $last = int sqrt $n;
for ( my $x = 5; $x <= $last ;) {
return $not_prime{ $n } = 0 if $n % $x == 0;
$x += 2;
return $not_prime{ $n } = 0 if $n % $x == 0;
$x += 4;
}
return $prime{ $n } = 1;
};
}
`

This version skips all of the numbers that are divisable by
2 and 3. Not checking numbers divisable by 2 is obvious, but not checking numbers divisable by 3 is less so, but reduces the search space by 25%.