SQL database of primes
So, I’m generating a SQL database of the first million primes as part of one of those random side tangents that I go off on occasionally. So far I’m up to half a million, and I’ve made several optimizations. I don’t know that my primefinder is actually valid, so I’m including it for you all to critique:
#!/usr/bin/perl
# version: 0.06
$debug = 1;
use DBI;
use Time::Local;
$dbh = DBI->connect(“dbi:mysql:db=primes”,undef,undef) || die “Failed to connect to database”;
$SIG{INT} = \&shutdown;
# first, locate our current position
($current) = $dbh->selectrow_array(“SELECT loc FROM current_location”);
$counter = $current;
#$lastprime = 1;
($lastprime) = $dbh->selectrow_array(“SELECT MAX(prime_number) FROM primes”);
$counter = ($lastprime + 1) if($lastprime > $counter);
while(1) {
if(is_prime($counter)) {
$span = $counter – $lastprime;
$lastprime = $counter;
log_prime($counter, $span);
print “$counter ($span)\n” if($debug);
}
if(! ($counter % 1000)) {
$dbh->do(“UPDATE current_location SET loc = $counter, ts = now()”);
}
$counter++;
}
sub is_prime {
my $number = shift;
# could use much improvement
return 0 if ($number == 1);
return 0 if (($number != 2) && (($number % 2) == 0));
# $maxprime = (int($number / 2) + 1);
$maxprime = (int(sqrt($number)) + 1);
# test against all known primes thus far
$sth = $dbh->prepare(“SELECT prime_number FROM primes WHERE prime_number < $maxprime"); $sth->execute();
while(($pp) = $sth->fetchrow_array()) {
# return 0 if(($number != $pp) && (int($number / $pp)) == ($number / $pp));
return 0 if(($number != $pp) && (($number % $pp) == 0));
}
$sth->finish();
return 1;
}
sub log_prime {
my $number = shift;
my $span = shift;
$dbh->do(“INSERT INTO primes VALUES (NULL,$number,$span,now())”);
}
sub shutdown {
$dbh->do(“UPDATE current_location SET loc = $counter, ts = now()”);
exit(0);
}