Recently for a project I started, I needed to find prime numbers. I'm not particularly worried about large prime numbers, but if someone asks for them, this module can be really slow. With caching, it speeds up quite a bit, but can still be slow the first time it hits a large number.
package Math::Name::To::Be::Determined;
use warnings;
use strict;
our $VERSION = '0.01';
use vars qw(@ISA @EXPORT_OK %EXPORT_TAGS);
use Exporter;
@ISA = 'Exporter';
@EXPORT_OK = qw(
clear_prime_cache
is_prime
primes_upto
);
%EXPORT_TAGS = (
all => \@EXPORT_OK,
);
{
my ( @PRIMES, %IS_PRIME );
clear_prime_cache();
sub is_prime {
my $number = shift;
return 1 if $IS_PRIME{$number};
return if $number < $PRIMES[-1];
my $is_prime;
for ( $PRIMES[-1] + 1 .. $number ) {
# cache prime numbers
if ( $is_prime = _is_prime($_) ) {
push @PRIMES => $_;
}
}
return $is_prime;
}
sub _is_prime {
my $number = shift;
return unless _is_integer($number);
return 1 if $IS_PRIME{$number};
return unless $number > 2 and $number % 2;
my $max = 1 + int $number**.5;
for ( my $divisor = 3; $divisor < $max; $divisor += 2 ) {
return unless $number % $divisor;
}
$IS_PRIME{$number} = 1; # cache it
return 1;
}
sub primes_upto {
my $number = shift;
if ( $number > $PRIMES[-1] ) {
# extend cache
is_prime($number);
}
my (@primes);
foreach my $i ( 0 .. @PRIMES ) {
next if $number > $PRIMES[$i];
@primes = @PRIMES[ 0 .. $i - 1 ] if $i;
last;
}
return wantarray ? @primes : \@primes;
}
sub clear_prime_cache {
@PRIMES = _get_primes();
%IS_PRIME = map { $_ => 1 } @PRIMES;
return;
}
}
sub _is_integer {
return shift =~ /^[-+]?\d+$/;
}
sub _get_primes {
# list from Crypt::Primes
# http://search.cpan.org/dist/Crypt-Primes/
return (
# huge list of all primes < 2^16
);
}
1;
This is part of a larger set of code which is intended to be pure Perl, but given that I'm not a mathematician, I'm not sure if this is the best approach. I make heavy use of caching and my tests pass, but I'm wondering if there is not a better approach to writing both &is_prime and &primes_upto. Even with heavy caching, finding primes significantly larger than 2^16 can be pretty slow.
-
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.
|