diff options
| author | Steven Wilson <steven1170@zoho.eu> | 2020-10-12 17:28:35 +0100 |
|---|---|---|
| committer | Steven Wilson <steven1170@zoho.eu> | 2020-10-12 17:28:35 +0100 |
| commit | feeb88b3fbce653093eabb00911f992a23a1ed0c (patch) | |
| tree | 43950634bc8a626b1a0abe1a9326936227bd6b42 | |
| parent | 2e7fb5ec844f60c121ef26d50e6b7f24b8849780 (diff) | |
| download | perlweeklychallenge-club-feeb88b3fbce653093eabb00911f992a23a1ed0c.tar.gz perlweeklychallenge-club-feeb88b3fbce653093eabb00911f992a23a1ed0c.tar.bz2 perlweeklychallenge-club-feeb88b3fbce653093eabb00911f992a23a1ed0c.zip | |
add solution week 82 task 1
| -rw-r--r-- | challenge-082/steven-wilson/perl/ch-1.pl | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/challenge-082/steven-wilson/perl/ch-1.pl b/challenge-082/steven-wilson/perl/ch-1.pl new file mode 100644 index 0000000000..92ca88a1de --- /dev/null +++ b/challenge-082/steven-wilson/perl/ch-1.pl @@ -0,0 +1,58 @@ +#!/usr/bin/env perl +# Week 82 Task 1 solution by Steven Wilson. + +=encoding utf8 + +=head1 TASK #1 › Common Factors +Submitted by: Niels van Dijke + +You are given 2 positive numbers $M and $N. + +Write a script to list all common factors of the given numbers. +Example 1: + +Input: + $M = 12 + $N = 18 + +Output: + (1, 2, 3, 6) + +Explanation: + Factors of 12: 1, 2, 3, 4, 6 + Factors of 18: 1, 2, 3, 6, 9 + +Example 2: + +Input: + $M = 18 + $N = 23 + +Output: + (1) + +Explanation: + Factors of 18: 1, 2, 3, 6, 9 + Factors of 23: 1 +=cut + +use strict; +use warnings; +use Test::More; +use Math::Factor::XS qw/ factors /; + +my @e1_t = qw/ 1 2 3 6 /; +my @e2_t = qw/ 1 /; +is_deeply( common_factors( 12, 18 ), \@e1_t, 'example 1' ); +is_deeply( common_factors( 18, 23 ), \@e2_t, 'example 2' ); +done_testing(); + +sub common_factors { + my ( $first, $second ) = @_; + my %first_factors = map { $_ => 1 } factors($first); + my @second_factors = factors($second); + my @intersection = sort { $a <=> $b } + grep { exists $first_factors{$_} } @second_factors; + unshift @intersection, 1; + return \@intersection; +} |
