Ethiopian multiplication: Difference between revisions

Line 1,264:
 
end program EthiopicMult</lang>
 
=={{header|FreeBASIC}}==
<lang FreeBASIC>Function double_(y As String) As String
Var answer="0"+y
Var addcarry=0
For n_ As Integer=Len(y)-1 To 0 Step -1
Var addup=y[n_]+y[n_]-96
answer[n_+1]=(addup+addcarry) Mod 10+48
addcarry=(-(10<=(addup+addcarry)))
Next n_
answer[0]=addcarry+48
Return Ltrim(answer,"0")
End Function
Function Accumulate(NUM1 As String,NUM2 As String) As String
Var three="0"+NUM1
Var two=String(len(NUM1)-len(NUM2),"0")+NUM2
Var addcarry=0
For n2 As Integer=len(NUM1)-1 To 0 Step -1
Var addup=two[n2]+NUM1[n2]-96
three[n2+1]=(addup+addcarry) Mod 10+48
addcarry=(-(10<=(addup+addcarry)))
Next n2
three[0]=addcarry+48
three=Ltrim(three,"0")
If three="" Then Return "0"
Return three
End Function
Function Half(Byref x As String) As String
Var carry=0
For z As Integer=0 To Len(x)-1
Var temp=(x[z]-48+carry)
Var main=temp Shr 1
carry=(temp And 1) Shl 3 +(temp And 1) Shl 1
x[z]=main+48
Next z
x= Ltrim(x,"0")
Return x
End Function
Function IsEven(x As String) As Integer
If x[Len(x)-1] And 1 Then Return 0
return -1
End Function
Function EthiopianMultiply(n1 As String,n2 As String) As String
Dim As String x=n1,y=n2
If Len(y)>Len(x) Then Swap y,x
'set the largest one to be halfed
If Len(y)=Len(x) Then
If x<y Then Swap y,x
End If
Dim As String ans
Dim As String temprint,odd
While x<>""
temprint=""
odd=""
If not IsEven(x) Then
temprint=" *"
odd=" <-- odd"
ans=Accumulate(y,ans)
End If
Print x;odd;tab(30);y;temprint
x=Half(x)
y= Double_(y)
Wend
Return ans
End Function
'================= Example ====================
Print
Dim As String s1="17"
Dim As String s2="34"
Print "Half";tab(30);"Double * marks those accumulated"
print "Biggest";tab(30);"Smallest"
Print
Var ans= EthiopianMultiply(s1,s2)
Print
Print
Print "Final answer"
Print " ";ans
print "Float check"
Print Val(s1)*Val(s2)
Sleep
</lang>note: algorithm uses strings instead of integers
{{out}}<pre>Half Double * marks those accumulated
Biggest Smallest
 
34 17
17 <-- odd 34 *
8 68
4 136
2 272
1 <-- odd 544 *
 
Final answer
578
Float check
578</pre>
 
=={{header|Go}}==
Anonymous user