Ethiopian multiplication: Difference between revisions

add E example
(add E example)
Line 195:
printf("%d\n", ethiopian(17, 34, true));
return 0;
}</lang>
 
=={{lang|E}}==
<lang e>def halve(&x) { x //= 2 }
def double(&x) { x *= 2 }
def even(x) { return x %% 2 <=> 0 }
 
def multiply(var a, var b) {
var ab := 0
while (a > 0) {
if (!even(a)) { ab += b }
halve(&a)
double(&b)
}
return ab
}</lang>
 
=={{header|Forth}}==
<lang forth>: e* ( x y -- x*y )
: e* ( x y -- x*y )
dup 0= if nip exit then
over 2* over 2/ recurse
swap 1 and if + else nip then ;</lang>
</lang>
 
The author of Forth, Chuck Moore, designed a similar primitive into his MISC Forth microprocessors. The '''+*''' instruction is a multiply step: it adds S to T if A is odd, then shifts both A and T right one. The idea is that you only need to perform as many of these multiply steps as you have significant bits in the operand. (See his [http://www.colorforth.com/inst.htm core instruction set] for details.)