Anonymous user
Ethiopian multiplication: Difference between revisions
→{{header|D}}
m (moved PowerShell after Powerbuilder (alphabetized)) |
|||
Line 622:
=={{header|D}}==
<lang d>
if (n1 < 0) {▼
int ethiopian(int n1, int n2)
throw new Exception("muliplier cannot be negative");▼
} body {
static int doubleNum(int n) pure { return n * 2; }▼
static int halveNum(int n) pure { return n / 2; }▼
static bool isEven(int n) pure { return !(n % 2); }▼
int result;▼
if (!isEven(n1))▼
result += n2;▼
n1 = halveNum(n1);▼
n2 = doubleNum(n2);▼
}
return result;▼
}
▲ int doubleNum(int n) { return n * 2; }
▲ int halveNum(int n) { return n / 2; }
▲ bool isEven(int n) { return !(n % 2); }
▲ int result;
assert(ethiopian(77, 54) == 77 * 54);▼
assert(ethiopian(64, -4) == 64 * -4);▼
▲ if (!isEven(n1))
▲ result += n2;
▲ n1 = halveNum(n1);
▲ n2 = doubleNum(n2);
▲ }
▲ return result;
}
void main() {
▲<lang d>unittest {
▲ assert(ethiopian(77, 54) == 77 * 54);
▲ assert(ethiopian(64, -4) == 64 * -4);
}</lang>
Output:
<pre>17 ethiopian 34 is 578</pre>
=={{header|E}}==
|