How to resolve the algorithm Ethiopian multiplication step by step in the Raku programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Ethiopian multiplication step by step in the Raku programming language
Table of Contents
Problem Statement
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
Method:
For example: 17 × 34 Halving the first column: Doubling the second column: Strike-out rows whose first cell is even: Sum the remaining numbers in the right-hand column: So 17 multiplied by 34, by the Ethiopian method is 578.
The task is to define three named functions/methods/procedures/subroutines:
Use these functions to create a function that does Ethiopian multiplication.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Ethiopian multiplication step by step in the Raku programming language
Source code in the raku programming language
sub halve (Int $n is rw) { $n div= 2 }
sub double (Int $n is rw) { $n *= 2 }
sub even (Int $n --> Bool) { $n %% 2 }
sub ethiopic-mult (Int $a is copy, Int $b is copy --> Int) {
my Int $r = 0;
while $a {
even $a or $r += $b;
halve $a;
double $b;
}
return $r;
}
say ethiopic-mult(17,34);
sub ethiopic-mult {
my &halve = * div= 2;
my &double = * *= 2;
my &even = * %% 2;
my ($a,$b) = @_;
my $r;
loop {
even $a or $r += $b;
halve $a or return $r;
double $b;
}
}
say ethiopic-mult(17,34);
sub halve { $^n div 2 }
sub double { $^n * 2 }
sub even { $^n %% 2 }
sub ethiopic-mult ($a, $b) {
[+] ($b, &double ... *)
Z*
($a, &halve ... 0).map: { not even $^n }
}
say ethiopic-mult(17,34);
You may also check:How to resolve the algorithm Sort stability step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Undefined values step by step in the OCaml programming language
You may also check:How to resolve the algorithm Padovan n-step number sequences step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the GEORGE programming language
You may also check:How to resolve the algorithm Man or boy test step by step in the Wren programming language