summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGuillermo Ramos2019-08-08 20:14:09 +0200
committerGuillermo Ramos2019-08-08 20:14:09 +0200
commit5b23e44824c4c74da7942be3ca215c4b12cd9641 (patch)
tree2a47bd9a9faf81a1de84b218676228de3a1f8ad8
parentf5ee0bc200f9f75654124b57c352fe5c965c122a (diff)
downloadperlweekly-5b23e44824c4c74da7942be3ca215c4b12cd9641.tar.gz
[020#2]
-rwxr-xr-x020/ch2.pl34
1 files changed, 34 insertions, 0 deletions
diff --git a/020/ch2.pl b/020/ch2.pl
new file mode 100755
index 0000000..d7bbb63
--- /dev/null
+++ b/020/ch2.pl
@@ -0,0 +1,34 @@
+#!/usr/bin/env perl
+#
+# Write a script to print the smallest pair of Amicable Numbers. For more
+# information, please checkout wikipedia page.
+#
+# (https://en.wikipedia.org/wiki/Amicable_numbers).
+################################################################################
+
+use strict;
+use warnings;
+
+sub sum_divisors {
+ my $n = shift;
+ my $sum = 0;
+ foreach my $i (1 .. $n/2) {
+ $sum += $i if $n % $i == 0;
+ }
+ return $sum;
+}
+
+my $n1 = 2;
+my $n2;
+my @already_checked;
+
+while (!$n2) {
+ my $sum = sum_divisors($n1);
+ if (!grep(/^$sum$/, @already_checked) && $sum != $n1 && sum_divisors($sum) == $n1) {
+ $n2 = $sum;
+ }
+ push @already_checked, $sum, $n1++;
+}
+$n1--;
+
+print "($n1, $n2)\n";