SumOfMultiples.pm (1087B) - raw
1 package SumOfMultiples; 2 use strict; 3 use warnings; 4 use Exporter qw<import>; 5 our @EXPORT_OK = qw<sum_of_multiples>; 6 7 sub sum_of_multiples { 8 # $input is a reference to a hash with two keys: factors and limit 9 # The value of factors is a reference to an array. Once we dereference 10 # that array, we can access the factors. 11 # The value of limit is the limit up to which we check the multiples. 12 my ($input) = @_; 13 my @factors = @{$input->{factors}}; 14 my $limit = $input->{limit}; 15 my %multiples = (); 16 my $sum_of_multiples = 0; 17 return $sum_of_multiples unless (@factors); # return 0 if empty array 18 foreach my $factor (@factors) { 19 # skip if current factor is greater than or equal to the limit, 20 next if $factor >= $limit; 21 next unless ($factor); # skip if factor equals 0 22 my $current = $factor; 23 while ($current < $limit) { 24 $multiples{$current} = $current; # add a multiple to the hash 25 $current += $factor; 26 } 27 } 28 foreach my $key (keys %multiples) { 29 $sum_of_multiples += $key; 30 } 31 return $sum_of_multiples; 32 } 33 34 1;