Sieve.pm (845B) - raw
1 package Sieve; 2 use strict; 3 use warnings; 4 use Exporter qw<import>; 5 our @EXPORT_OK = qw<find_primes>; 6 7 sub find_primes { 8 my ($limit) = @_; 9 return [ ] if ( $limit == 1 ); # no primes under 2 10 return [ 2 ] if ( $limit == 2); 11 12 # initialize our sieve as a hash with a default value of `1`, assuming 13 # for now that all numbers within the range are prime 14 my %sieve = map { $_ => 1 } ( 2 .. $limit ); 15 16 foreach my $candidate ( 2 .. $limit ) { 17 my $multiple = $candidate * 2; # start at next multiple 18 while ( $multiple <= $limit ) { 19 $sieve{ $multiple } = 0; 20 $multiple += $candidate; 21 } 22 } 23 24 # store in array @primes all keys of `%sieve` where $sieve{ $_ } is 25 # still equal to 1, indicating that the key is a prime number 26 my @primes = sort { $a <=> $b } grep{ $sieve{ $_ } } keys %sieve; 27 28 return \@primes; 29 } 30 31 1;