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%.
-
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.
|