blob: 2ad8a0f3af59facc0094e0f47c3403e1d2453a7c (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
━━━━━━━━━━━━━━━
CHALLENGE 082
Andinus
━━━━━━━━━━━━━━━
Table of Contents
─────────────────
1. Task 1 - Common Factors
.. 1. Perl
1 Task 1 - Common Factors
═════════════════════════
You are given 2 positive numbers $M and $N.
Write a script to list all common factors of the given numbers.
1.1 Perl
────────
• Program: <file:perl/ch-1.pl>
We loop over all the numbers from `1 ... $M' to get their factors &
then just compare it with factors of `$N'. I took this code from
Challenge 081's ch-1.pl.
┌────
│ my $A = shift @ARGV;
│ my $B = shift @ARGV;
│
│ # Get all common divisors.
│ my %divisors_of_A = divisors($A);
│ my %divisors_of_B = divisors($B);
│ my @common_divisors;
│ foreach my $num (sort { $a <=> $b } keys %divisors_of_A) {
│ push @common_divisors, $num
│ if exists $divisors_of_B{$num};
│ }
│
│ # Returns all divisors of a number.
│ sub divisors {
│ my $n = shift @_;
│ my %divisors;
│ foreach my $i ( 1 ... $n){
│ if ($n % $i == 0) {
│ $divisors{$i} = 1;
│ }
│ }
│ return %divisors;
│ }
│
│ print join(', ', @common_divisors), "\n";
└────
|