whats wrong with this program to make big multiplications?

antonio gonzalez 136 Reputation points
2021-02-23T15:59:49.623+00:00

i cant figure out what im doing wrong

re:
mult1=123
mult2=111
For i=0 To Text.GetLength(mult1)-1
arr1[i]=Text.GetSubText(mult1,i+1,1)
EndFor
For i=0 To Text.GetLength(mult2)-1
arr2[i]=Text.GetSubText(mult2,i+1,1)
EndFor

For i=0 To Array.GetItemCount(arr1)-1

For j=0 to Array.GetItemCount(arr2)-1

    ans[i+j]=ans[i+j]+arr1[i]*arr2[j]
    ans[i+j+1]=ans[i+j+1]+Math.Floor( ans[i+j]/10)
    ans[i+j]=Math.Remainder(ans[i+j],10)
    EndFor

EndFor

For i=0 to Array.GetItemCount(ans)-1
ans2=Text.Append(ans2,ans[i])

EndFor

TextWindow.WriteLine(ans2)

im translating from this:

for(int i=0;i<arr1_length;i++)
{
for(int j=0;j<arr2_length;j++)
{

    ans[i+j]+=arr1[i]*arr2[j];
    ans[i+j+1]=ans[i+j+1]+ans[i+j]/10;
    ans[i+j]%=10;
}

}

Small BASIC
Small BASIC
A programming language created by Microsoft that serves a stepping stone for beginners from block-based coding languages to more complex text-based languages.
279 questions
0 comments No comments
{count} votes

Accepted answer
  1. WhTurner 1,611 Reputation points
    2021-02-25T12:49:56.253+00:00

    In a manual (pen and paper) multiplication you start at the right with the unit digits and and add the carry to the left.
    Your program starts with the most significant digits and the carry to the right. That is obviously not the same, and gives wrong answers.

    I changed the multiplication loops to

    For i= Array.GetItemCount(arr1)-1 to 0 step -1  ''invers direction
      For j=Array.GetItemCount(arr2)-1 to 0 step -1
        ans[i+j]=ans[i+j]+arr1[i]*arr2[j]
        ans[i+j-1]=ans[i+j-1]+Math.Floor( ans[i+j]/10)   ''carry to the left (2 minus signs)
        ans[i+j]=Math.Remainder(ans[i+j],10)
      EndFor
    EndFor`
    

    The last carry goes to ans[-1] so you have to change the output loop from -1 to the last digit.

    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful