SPUG: Primes

Doug Treder dtreder at gmail.com
Sat Oct 6 10:50:59 PDT 2007


Maybe this was unintentional, but I found it hilarious.

For those not in on the joke, this algorithm is (or is very similar to) 
the Sieve of Erastothenes, and is widely known as the earliest known 
algorithm of any kind (not just for finding prime numbers).

I show this one in my last class as an example of coding in 
Lingua::Romana::Perligata, a fun module by Damian Conway.   It's very 
succinct as:

#!/usr/bin/perl
# Sieve of Eratosthenes
print STDOUT 'maximum:';                
my $maxim = <STDIN>;                    
my (@list) = (2..$maxim);
while ($next = shift @list)            
  {
      print STDOUT $next, "\n";
      @list = grep {$_ % $next} @list;
  }

which is the literal translation, using Lingua::Romana::Perligata of:

#! /usr/local/bin/perl -w
use Lingua::Romana::Perligata;
adnota Illud Cribrum Eratothenis
maximum inquementum tum biguttam egresso scribe.
    meo maximo vestibulo perlegamentum da.
    da duo tum maximum conscribementa meis listis.
    dum listis decapitamentum damentum nexto
        fac sic
            nextum tum novumversum scribe egresso.
            lista sic hoc recidementum nextum cis
               vannementa da listis.
        cis.


(original code and translation from Damian Conway)

-Doug



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 Getopt::Std;
> use vars '$opt_p';
> use strict;
>
> # Annoying hidden voodoo.
> getopts('p:');
>
> ($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];
>     }
>
>     return;
> }
>
> while ($i < $opt_p) {
>
>     if (exists $numbers{$i}) {
>         map next_number($i,$_), @{$numbers{$i}};
>         delete $numbers{$i};
>     }
>     else {
>         printf "%8d\n", $i;
>         next_number($i,$i);
>     }
>
>     $i += 1;
> }
>
> exit(0);
>
> _____________________________________________________________
> Seattle Perl Users Group Mailing List  
>      POST TO: spug-list at pm.org
> SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
>     MEETINGS: 3rd Tuesdays
>     WEB PAGE: http://seattleperl.org/
>
>   



More information about the spug-list mailing list