Ethiopian multiplication: Difference between revisions

m (→‎{{header|OCaml}}: indentation)
(→‎{{header|PowerShell}}: Added PureBasic)
Line 1,355:
 
multiplyValues 17 34</lang>
=={{header|PureBasic}}==
<lang PureBasic>Procedure isOdd(x)
ProcedureReturn x & 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 isOdd(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>
Sample output:
<pre>Ethiopian multiplication of 17 and 34 ... equals 578</pre>
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 isOdd(x)
ProcedureReturn x & 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 isOdd(x)
sum + y
Else
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>
Sample output:
<pre>Ethiopian multiplication of 17 and 34 ... equals 578
Ethiopian multiplication of -17 and 34 ... equals -578
Ethiopian multiplication of -17 and -34 ... equals 578</pre>
 
=={{header|Python}}==
Anonymous user