Apr 012008
 

#!/usr/bin/perl
use strict;
use warnings;
use Carp;
{
   my $sieve;
   my $number; #Initializing number to 2 would require additional logic

   sub handlesieve
   {
      while (exists $sieve->{$number})
      {
         for my $multiple ( @{$sieve->{$number}} )
         {
            push @{$sieve->{$number+$multiple}}, $multiple;
         }
         delete $sieve->{$number};
         $number += 2;
      }
      $sieve->{$number * $number} = [ 2 * $number ];
      return;
   }

   sub prime
   {
      if (not defined $number)
      {
         $number = 2;
      }
      elsif ($number == 2)
      {
         $number = 3;
         {
            no warnings;
            *prime = &prime_2;
         }
      }
      else
      {
         croak "Illegal calln";
      }
      handlesieve();
      return $number;
   }

   sub prime_2
   {
      $number += 2;
      handlesieve();
      return $number;
   }
}

#
# Print the first $max primes
#
my $max = shift || 100;

for ( 1 .. $max )
{
   printf "%dn",prime();
}

L’implementazione del Crivello di Atkin è lasciata come esercizio per il lettore.

Sorry, the comment form is closed at this time.