Well, i just wrote my own prime checker that is really a growing sieve that goes as far as it needs to for the prime to check. It caches a hash of all the primes known so far, so that primeness only needs to be calculated once, and is quite fast. I didnt even bother explicitly eliminating even numbers in advance, but that would be no biggie. The general sieve'ing can be improved some too.
So here it is:
{
my %prime_cache;
my $max_checked;
BEGIN {
$prime_cache{2} = undef;
$max_checked = 2;
}
sub is_prime {
my ($to_check) = @_;
sieve_up_to($to_check);
return exists $prime_cache{$to_check};
}
sub sieve_up_to {
my ($to_check) = @_;
while ( $max_checked < $to_check ) {
sieve_part($to_check);
}
}
sub sieve_part {
my ($to_check) = @_;
$to_check++ if !($to_check % 2);
my $max_this_part = $to_check;
if ( ($max_checked * $max_checked) < $to_check ) {
$max_this_part = $max_checked * $max_checked;
}
my %to_sieve = map { $_ => undef } ($max_checked + 1 .. $max_t
+his_part);
for my $prime (keys %prime_cache) {
my $base = $max_checked - ($max_checked % $prime) + $prime
+;
while ( $base <= $max_this_part ) {
delete $to_sieve{$base};
$base += $prime;
}
}
while ( my $new_prime = each %to_sieve ) {
$prime_cache{$new_prime} = undef;
}
$max_checked = $max_this_part;
}
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|