Ethiopian multiplication: Difference between revisions

Line 2,963:
writeln(Z).</lang>Even this is more verbose than what a more native solution would look like.
 
=={{header|PureBasic}}==
<lang PureBasic>Procedure isEven(x)
ProcedureReturn (x & 1) ! 1
EndProcedure
 
Procedure halveValue(x)
ProcedureReturn x / 2
EndProcedure
 
Procedure doubleValue(x)
ProcedureReturn x << 1
EndProcedure
 
Procedure EthiopianMultiply(x, y)
Protected sum
Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ... ")
Repeat
If Not isEven(x)
sum + y
EndIf
x = halveValue(x)
y = doubleValue(y)
Until x < 1
PrintN(" equals " + Str(sum))
ProcedureReturn sum
EndProcedure
 
If OpenConsole()
EthiopianMultiply(17,34)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</lang>
{{out}}
Ethiopian multiplication of 17 and 34 ... equals 578
It became apparent that according to the way the Ethiopian method is described above it can't produce a correct result if the first multiplicand (the one being repeatedly halved) is negative. I've addressed that in this variation. If the first multiplicand is negative then the resulting sum (which may already be positive or negative) is negated.
<lang PureBasic>Procedure isEven(x)
ProcedureReturn (x & 1) ! 1
EndProcedure
 
Procedure halveValue(x)
ProcedureReturn x / 2
EndProcedure
 
Procedure doubleValue(x)
ProcedureReturn x << 1
EndProcedure
 
Procedure EthiopianMultiply(x, y)
Protected sum, sign = x
Print("Ethiopian multiplication of " + Str(x) + " and " + Str(y) + " ...")
Repeat
If Not isEven(x)
sum + y
EndIf
x = halveValue(x)
y = doubleValue(y)
Until x = 0
If sign < 0 : sum * -1: EndIf
PrintN(" equals " + Str(sum))
ProcedureReturn sum
EndProcedure
 
If OpenConsole()
EthiopianMultiply(17,34)
EthiopianMultiply(-17,34)
EthiopianMultiply(-17,-34)
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf</lang>
{{out}}
Ethiopian multiplication of 17 and 34 ... equals 578
Ethiopian multiplication of -17 and 34 ... equals -578
Ethiopian multiplication of -17 and -34 ... equals 578
=={{header|Python}}==
===Python: With tutor===
Anonymous user