Jump to content

Ethiopian multiplication: Difference between revisions

Updated D code
(→‎{{header|GW-BASIC}}: Marked incorrect)
(Updated D code)
Line 705:
 
=={{header|D}}==
<lang d>import std.stdio: writeln;
Works with DMD V.2.051.
<lang d>import std.stdio: writeln;
 
pure nothrow int ethiopian(int n1, int n2)
in {
assert(n1 >= 0, "muliplier cannot be negative");
} body {
static pure nothrow int doubleNum(constin int n) { return n * 2; }
static pure nothrow int halveNum(constin int n) { return n / 2; }
static pure nothrow bool isEven(constin int n) { return !(n % 2); }
 
int result;
while (n1 >= 1) {
if (!isEven(n1))
result += n2;
n1 = halveNum(n1);
n2 = doubleNum(n2);
}
 
return result;
while (n1 >= 1) {
}
if (!isEven(n1))
result += n2;
n1 = halveNum(n1);
n2 = doubleNum(n2);
}
 
return result;
}
 
unittest {
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.