aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2020-12-07 17:30:45 +0100
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2020-12-09 16:38:28 +0100
commitd044d074f9325d9b8cf0f9d324a23297761b7258 (patch)
treefa4e5c4b5e7550792c1ccd5bb55f8e51221f42b2
parent5e03fe60134769d22eb9c118ea88f737593b2c04 (diff)
downloadperlweeklychallenge-club-d044d074f9325d9b8cf0f9d324a23297761b7258.tar.gz
perlweeklychallenge-club-d044d074f9325d9b8cf0f9d324a23297761b7258.tar.bz2
perlweeklychallenge-club-d044d074f9325d9b8cf0f9d324a23297761b7258.zip
Solution to task 2
-rwxr-xr-xchallenge-090/jo-37/perl/ch-2.pl28
1 files changed, 28 insertions, 0 deletions
diff --git a/challenge-090/jo-37/perl/ch-2.pl b/challenge-090/jo-37/perl/ch-2.pl
new file mode 100755
index 0000000000..e1d3865f81
--- /dev/null
+++ b/challenge-090/jo-37/perl/ch-2.pl
@@ -0,0 +1,28 @@
+#!/usr/bin/perl
+
+use integer;
+use Test2::V0;
+
+# Implement Ethiopian multiplication
+sub ethiopian_mult {
+ my ($p, $q) = splice @_, 0, 2;
+ # The method is more effective if the first number is the smaller
+ # one.
+ ($p, $q) = ($q, $p) if $p > $q;
+
+ my $prod = 0;
+ while ($p) {
+ # Add second number if the first is odd
+ $prod += ($p % 2) * $q;
+ # Get next pair.
+ ($p, $q) = ($p / 2, $q * 2);
+ }
+
+ $prod;
+}
+
+is ethiopian_mult(14, 12), 168, 'Example 1';
+is ethiopian_mult(2**32, 0), 0, 'Multiply by zero';
+is ethiopian_mult(2**32, 1), 2**32, 'Multiply by one';
+
+done_testing;