exercism-perl5

Repository for my Perl 5 Exercism exercises
git clone git://git.samirparikh.com/exercism-perl5
Log | Files | Refs | README

commit a51078da241dce34a49be3de9f87c0c7e4856240
parent 70d183143d2656c2874489a5eac500cf969b064e
Author: Samir Parikh <noreply@samirparikh.com>
Date:   Thu, 26 May 2022 13:18:25 +0000

get all tests to pass

Diffstat:
Msieve/Sieve.pm | 23++++++++++++++++++++++-
1 file changed, 22 insertions(+), 1 deletion(-)

diff --git a/sieve/Sieve.pm b/sieve/Sieve.pm @@ -4,9 +4,30 @@ use warnings; use Exporter qw<import>; our @EXPORT_OK = qw<find_primes>; +#use Data::Dumper; + sub find_primes { my ($limit) = @_; - return undef; + return [ ] if ( $limit == 1 ); # no primes under 2 + return [ 2 ] if ( $limit == 2); + + # initialize our sieve as a hash with a default value of `1`, assuming + # for now that all numbers within the range are prime + my %sieve = map { $_ => 1 } ( 2 .. $limit ); + + foreach my $candidate ( 2 .. $limit ) { + my $multiple = $candidate * 2; # start at next multiple + while ( $multiple <= $limit ) { + $sieve{ $multiple } = 0; + $multiple += $candidate; + } + } + + # store in array @primes all keys of `%sieve` where $sieve{ $_ } is + # still equal to 1, indicating that the key is a prime number + my @primes = sort { $a <=> $b } grep{ $sieve{ $_ } } keys %sieve; + + return \@primes; } 1;