gam3,
I have added several improvements:
 Cache is now persistent
 Primeness is determined in C
 The 2 4 trick is used in checking near numbers also
 An iterator is used in lieu of a stack
#!/usr/bin/perl
use strict;
use warnings;
use DBM::Deep;
use Inline C =>;
my $prime = DBM::Deep>new( 'primes.db' );
#$prime>{is}{$_} = 1 for (2, 3, 5, 7, 11, 13, 17, 19, 23); # 1st run
+only
my $next = find_near_primes(10000 => 100);
while ( my $p = $next>() ) {
print "$p\n";
}
sub find_near_primes {
my ($num, $tot) = @_;
my ($below, $above, $up, $down);
my $by_2_4 = sub { my $n = shift; return sub { return $n = $n == 2
+ ? 4 : 2 } };
my $dir = 1;
return sub {
return () if ! $tot;
$dir *= 1;
if ( $num ) {
$num = $num  $num % 3;
$num += not ($num % 2) ? 1 : 2;
($below, $above, $num) = ($num, $num, undef);
($up, $down) = ($by_2_4>( 4 ), $by_2_4>( 2 ));
$below = $down>();
}
if ( $dir == 1  $below < 5 ) {
if ( ! $prime>{is}{$above} ) {
$above += $up>() while $prime>{not}{$above};
while ( ! is_prime( $above ) ) {
$prime>{not}{$above} = 1;
$above += $up>() while $prime>{not}{$above};
last if $prime>{is}{$above};
}
$prime>{is}{$above} = 1;
}
my $p = $above;
$above += $up>() and return $p;
}
else {
if ( ! $prime>{is}{$below} ) {
$below = $down>() while $prime>{not}{$below};
while ( ! is_prime( $below ) ) {
$prime>{not}{$below} = 1;
$below = $down>() while $prime>{not}{$below};
last if $prime>{is}{$below};
}
$prime>{is}{$below} = 1;
}
my $p = $below;
$below = $down>() and return $p;
}
};
}
__END__
__C__
#include <math.h>
short is_prime (unsigned long num) {
unsigned long i = 5;
unsigned long j = sqrt( num );
while ( i <= j ) {
if ( num % i == 0 ) return 0;
i += 2;
if ( num % i == 0 ) return 0;
i += 4;
}
return 1;
}
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.
Please read these before you post! —
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?
See Writeup Formatting Tips and other pages linked from there for more info.

Log In^{?}


Chatterbox^{?}

How do I use this?  Other CB clients

Other Users^{?}

Others romping around the Monastery: (7) As of 20170924 18:13 GMT

Sections^{?}


Information^{?}


Find Nodes^{?}


Leftovers^{?}


Voting Booth^{?}


Notices^{?}


