diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2020-10-14 21:50:28 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2020-10-14 21:50:28 +0100 |
| commit | 2dd0672a5a89236c21eab466ba81a4c66cf873aa (patch) | |
| tree | 93b0c19c077351315ee628c9e9793ed40d61e286 | |
| parent | d1c1eafd275aac25a83e9ceb4e50b6390a7f9e8a (diff) | |
| parent | 35851d7c398ddc80b93e0a7bc64731d3093d832a (diff) | |
| download | perlweeklychallenge-club-2dd0672a5a89236c21eab466ba81a4c66cf873aa.tar.gz perlweeklychallenge-club-2dd0672a5a89236c21eab466ba81a4c66cf873aa.tar.bz2 perlweeklychallenge-club-2dd0672a5a89236c21eab466ba81a4c66cf873aa.zip | |
Merge pull request #2526 from LubosKolouch/master
Challenge 082 Task 1 Perl LK
| -rw-r--r-- | challenge-082/lubos-kolouch/perl/ch-1.pl | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/challenge-082/lubos-kolouch/perl/ch-1.pl b/challenge-082/lubos-kolouch/perl/ch-1.pl new file mode 100644 index 0000000000..c03e06cc28 --- /dev/null +++ b/challenge-082/lubos-kolouch/perl/ch-1.pl @@ -0,0 +1,48 @@ +#!/usr/bin/perl +#=============================================================================== +# +# FILE: ch-1.pl +# +# USAGE: ./ch-1.pl +# +# DESCRIPTION: Perl Weekly Challenge 082 +# http://www.perlweeklychallenge.org +# Task 1 - Common Factors +# +# AUTHOR: Lubos Kolouch +# CREATED: 10/14/2020 07:25:23 PM +#=============================================================================== + +use strict; +use warnings; + +sub get_common_factors { + my $numbers = shift; + + # 1 is always factor + my @common_factors = (1); + + # it's enough to to go sqrt of one of the numbers + for (2..int(sqrt($numbers->{'first'}))) { + next unless $numbers->{'first'} % $_ == 0; + + # add to solution if it is factor of the second number + push @common_factors, $_ if $numbers->{'second'} % $_ == 0; + + # the same for the "other factor" + my $other_factor = $numbers->{'first'} / $_; + push @common_factors, $other_factor if $numbers->{'second'} % $other_factor == 0; + } + + # return them in the right order + @common_factors = sort {$a <=> $b} @common_factors; + return \@common_factors; +} + +use Test::More; + +is_deeply(get_common_factors( { first => 12, second => 18 } ), [1,2,3,6]); +is_deeply(get_common_factors( { first => 18, second => 23 } ), [1]); +is_deeply(get_common_factors( { first => 1, second => 1 } ), [1]); + +done_testing; |
