note
blazar
<BLOCKQUOTE><I>There is no way of predicting what the next prime number is, given any other number. If there was, then current cryptography methods wouldn't work. All prime number generators are, for the most part, variations on brute force. The method you're looking at is probably as good as any.</I></BLOCKQUOTE>
<P>Huh?!? You're joking, aren't you? The same fact that you say <EM>"all prime number generators are, for the most part, variations on brute force"</EM> is in contradiction with the claim that <EM>"there is no way of predicting what the next prime number is, given any other number"</EM>.
<P>More precisely if I have <EM>any</EM> <CODE>isprime()</CODE> sub, e.g.
<CODE>
sub isprime {
my $n=shift;
return undef if abs $n == 1;
return isprime -$n if $n<0;
return 0 if $n == 0;
$n%$_ or return 0 for (2..sqrt $n);
1;
}
</CODE>
(I'm not posting a better one for others already have, and even better ones are available elsewhere.)
or the witty
<CODE>
sub isprime {
(1 x shift) !~ /^1?$|^(11+?)\1+$/;
}
</CODE>
(this is Abigail's - who else?)
then a sub like this:
<CODE>
sub nearest_prime {
my $n=my $m=shift;
return $n if isprime $n;
while (1) {
return $n if isprime ++$n;
return $m if isprime --$m;
}
}
</CODE>
would answer the OP's question.
<P><STRONG>Important:</STRONG> not only primality testing algorithms <EM>do</EM> exist, but <EM>fast ones</EM> exist too. What <EM>in some sense</EM> there is "no way" to do is to <EM>factorize</EM> a composite number which is a different problem. But really even for the latter problem there are perfectly deterministic algorithms. "Only" it is <EM>believed</EM> to be <EM>computationally "hard"</EM> (in a mathematically precise sense), whereas the former is not. It is on this last <EM>conjecture</EM> (not proved yet!) that many cryptography methods rely.
<P>Since the OP did not specify the size of a problem, but gave an example with small numbers, an effective answer in terms of some efficient sieving algorithm <EM>can</EM> be given.
430254
430267