The Sieve of Eratosthenes

polettix on 2007-02-20T23:43:46

Translating a python function for a sieve of eratosthenes (a way to detect prime numbers), I've come up with this:

sub eratosthenes {
   my %D;
   my $q = 2;
   return sub {
      while (defined(my $p = delete $D{$q})) {
         my $x = $p + $q;
         $x += $p while exists $D{$x};
         $D{$x} = $p;
         ++$q;
      } ## end while (defined(my $p = delete...
      $D{$q * $q} = $q;
      return $q++;
   };
} ## end sub eratosthenes


It's nice, even if it tends to blow for increasing values (due to memory requirements).