Anonymous Monk,
Ok - this is an adaptation of Challenge: Nearest Palindromic Number. Since the mathematical lesson has already been explained, I decided to spruce up the Perl so that there might be a lesson in it.
#!/usr/bin/perl
use strict;
use warnings;
my $nearest_prime = nearest();
for ( map { int( rand 9998 ) + 2 } 1 .. 50 ) {
print "$_ : ", $nearest_prime->( $_ ), "\n";
}
sub nearest {
my $prime = is_prime();
return sub {
my $n = shift;
return $n if $prime->( $n );
my $pos = $n;
++$pos while ! $prime->( $pos );
$pos = $pos - $n;
my $neg = $n;
--$neg while ! $prime->( $neg );
$neg = $n - $neg;
return $pos > $neg ? $n - $neg : $n + $pos;
}
}
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 || exists $not_prime{ $n };
for ( 3 .. sqrt $n ) {
return $not_prime{ $n } = 0 if $n % $_ == 0;
}
return $prime{ $n } = 1;
};
}
I will leave converting the code from the nearest prime to the nearest N primes as an exercise for the reader.
-
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.
|