<?xml version="1.0" encoding="windows-1252"?>
<node id="430317" title="Re: a close prime number" created="2005-02-11 17:03:48" updated="2005-05-02 10:56:05">
<type id="11">
note</type>
<author id="391408">
TedPride</author>
<data>
<field name="doctext">
&lt;code&gt;
use strict;
use warnings;

print nearPrime(100000);

sub nearPrime {
    my $num = shift; $_ = 0;
    return $num if isPrime($num);
    while (1) {
        $_++;
        return ($num - $_) if isPrime($num - $_);
        return ($num + $_) if isPrime($num + $_);
    }
}

BEGIN {
    my @primes = (2); my $max = 2;
    sub isPrime {
        my $num = shift;
        my $root = int sqrt $num;
        if ($root &gt; $max) {
            for (($max+1)..$root) {
                 push(@primes, $_) if isPrime($_);
            }
            $max = $root;
        }
        for (@primes) {
            return 0 if ($num % $_ == 0);
        }
        return 1;
    }
}
&lt;/code&gt;</field>
<field name="root_node">
430254</field>
<field name="parent_node">
430254</field>
</data>
</node>
