SPUG: Primes
John W. Krahn
krahnj at telus.net
Sat Oct 6 04:34:55 PDT 2007
Fred Morris wrote:
> 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.
>
> #!/usr/bin/perl
> # Expects -p:max-to-test where max-to-test is an integer.
use warnings;
> use Getopt::Std;
> use vars '$opt_p';
> use strict;
>
> # Annoying hidden voodoo.
> getopts('p:');
Or without the package variable:
getopts( 'p:', \my %opt );
> ($opt_p =~ m/^\d+$/) or die 'p must be an unsigned decimal integer';
>
> my $i = 2; # First possible value.
> my %numbers;
>
> sub next_number($$) {
Don't use prototypes. With warnings enabled this will warn.
> 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];
> }
No need to test for key existence, perl will autovivify the array.
my $next_i = $i + $k;
push @{ $numbers{ $next_i } }, $k;
> return;
> }
>
> while ($i < $opt_p) {
>
> if (exists $numbers{$i}) {
> map next_number($i,$_), @{$numbers{$i}};
Where is the list that map returns being assigned?
> delete $numbers{$i};
next_number( $i, $_ ) for @{ delete $numbers{ $i } };
> }
> else {
> printf "%8d\n", $i;
> next_number($i,$i);
> }
>
> $i += 1;
> }
>
> exit(0);
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
More information about the spug-list
mailing list