SPUG: Primes

Fred Morris m3047 at inwa.net
Sat Oct 6 01:00:22 PDT 2007

Somebody told me this wasn't math, just accounting. But I can't seem to find 
it exactly described in the literature. Have fun. Let me know.

# Expects -p:max-to-test where max-to-test is an integer.

use Getopt::Std;
use vars '$opt_p';
use strict;

# Annoying hidden voodoo.

($opt_p =~ m/^\d+$/) or die 'p must be an unsigned decimal integer';

my $i = 2; # First possible value.
my %numbers;

sub next_number($$) {

    my $i = shift;
    my $k = shift;

    my $next_i = $i + $k;
    if (exists $numbers{$next_i}) {
        push @{$numbers{$next_i}}, $k;
    else {
        $numbers{$next_i} = [$k];


while ($i < $opt_p) {

    if (exists $numbers{$i}) {
        map next_number($i,$_), @{$numbers{$i}};
        delete $numbers{$i};
    else {
        printf "%8d\n", $i;

    $i += 1;


More information about the spug-list mailing list