Ethiopian multiplication: Difference between revisions

m (Remove surrounding newlines)
Line 4,117:
echo ethiopian_multiply::init(17, 34);
?></lang>
 
=={{header|Picat}}==
<lang Picat>go =>
 
println(ethiopian(17,34)),
 
ethiopian2(17,34,Z2),
println(Z2),
println(ethiopian(17,34,true)),
 
_ = random2(),
_ = ethiopian(random() mod 10000,random() mod 10000,true),
 
nl.
 
 
ethiopian(Multiplier, Multiplicand) = ethiopian(Multiplier, Multiplicand,false).
 
ethiopian(Multiplier, Multiplicand,Tutor) = Result =>
if Tutor then
printf("\n%d * %d:\n",Multiplier, Multiplicand)
end,
Result1 = 0,
while (Multiplier >= 1)
OldResult = Result1,
if not even(Multiplier) then
Result1 := Result1 + Multiplicand
end,
if Tutor then
printf("%6d % 8s\n",Multiplier,cond(OldResult=Result1,"--",Multiplicand.to_string()))
end,
Multiplier := halve(Multiplier),
Multiplicand := double(Multiplicand)
end,
if Tutor then
println(" ======="),
printf(" %8s\n",Result1.to_string()),
nl
end,
Result = Result1.
 
 
% Inspired by the Prolog solution
ethiopian2(First,Second,Product) =>
ethiopian2(First,Second,0,Product).
 
ethiopian2(1,Second,Sum0,Sum) =>
Sum = Sum0 + Second.
ethiopian2(First,Second,Sum0,Sum) =>
Sum1 = Sum0 + Second*(First mod 2),
ethiopian2(halve(First), double(Second), Sum1, Sum).
 
halve(X) = X div 2.
double(X) = 2*X.
is_even(X) => X mod 2 = 0.</lang>
 
Output:
<pre>578
578
 
17 * 34:
17 34
8 --
4 --
2 --
1 544
=======
578
 
578
 
5516 * 9839:
5516 --
2758 --
1379 39356
689 78712
344 --
172 --
86 --
43 1259392
21 2518784
10 --
5 10075136
2 --
1 40300544
=======
54271924</pre>
 
 
=={{header|PicoLisp}}==
495

edits