good chemistry is complicated,and a little bit messy -LW PerlMonks

Comment on

 Need Help??
I think yours is working a little harder than necessary. (Update: I didn't recognize the cache.) Also note that you ought to localize \$_ if you're going to use it where Perl isn't automatically localizing it.
```for (10,15,20831323,99,100) {
print "\$_: ", nearPrime(\$_), "\n";
}

sub nearPrime {
my \$num = shift;
local \$_ = 0; # otherwise tries to modify for loop var above
return \$num if isPrime(\$num);
while (1) {
\$_++;
return (\$num - \$_) if isPrime(\$num - \$_);
return (\$num + \$_) if isPrime(\$num + \$_);
}
}

...
An alternative nearPrime sub:
```sub nearPrime {
my \$num = shift;
my \$sign = 1;
return \$num if isPrime(\$num);
for (0..\$num) {
\$num += \$sign * \$_;
return \$num if isPrime(\$num);
\$sign = -\$sign;
}
}
And this isPrime does a little less work by checking only odd numbers:
```BEGIN {
my @primes = (2, 3); my \$max = 3;
sub isPrime {
my \$num = shift;
my \$root = int sqrt \$num;
while (\$max <= \$root) {
\$max += 2;
push(@primes, \$max) if isPrime(\$max);
}
for (@primes) {
last if \$_ > \$root;
return 0 if (\$num % \$_ == 0);
}
return 1;
}
}

Caution: Contents may have been coded under pressure.

In reply to Re^2: a close prime number by Roy Johnson
in thread a close prime number by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and the daffodils sway...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2018-04-20 17:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (77 votes). Check out past polls.

Notices?