<?xml version="1.0" encoding="windows-1252"?>
<node id="430327" title="Re: a close prime number" created="2005-02-11 17:29:37" updated="2005-05-01 13:58:44">
<type id="11">
note</type>
<author id="180961">
Limbic~Region</author>
<data>
<field name="doctext">
[Anonymous Monk],
&lt;br /&gt;
Ok - this is an adaptation of [id://427378].  Since the mathematical lesson has already been explained, I decided to spruce up the Perl so that there might be a lesson in it.
&lt;CODE&gt;
#!/usr/bin/perl
use strict;
use warnings;

my $nearest_prime = nearest();

for ( map { int( rand 9998 ) + 2 } 1 .. 50 ) {
    print "$_ : ", $nearest_prime-&gt;( $_ ), "\n";
}

sub nearest {
    my $prime = is_prime();
    return sub {
        my $n = shift;
        return $n if $prime-&gt;( $n );
        my $pos = $n;
        ++$pos while ! $prime-&gt;( $pos );
        $pos = $pos - $n;
        my $neg = $n;
        --$neg while ! $prime-&gt;( $neg );
        $neg = $n - $neg;
        return $pos &gt; $neg ? $n - $neg : $n + $pos;
    }
}

sub is_prime {
    my %prime = map { $_ =&gt; 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;
    };
}
&lt;/CODE&gt;
I will leave converting the code from the &lt;i&gt;nearest&lt;/i&gt; prime to the nearest N primes as an exercise for the reader.
&lt;div class="pmsig"&gt;&lt;div class="pmsig-180961"&gt;
&lt;p&gt;
Cheers - [Limbic~Region|L~R]
&lt;/p&gt;
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
430254</field>
<field name="parent_node">
430254</field>
</data>
</node>
