I’m implementing the simple multiplication algorithm to compare its performance to a divide and conquer approach.
I ditched my original idea to do this thing with byte arithmetic and opted to convert the numbers via char arrays.
Well, everything works fine on simple cases like 33 x 33, where the debugging method prints, correctly:
0 9 9
0 9 9
yet on 34 x 33, I get
1 0 3
1 0 2
where it should be
1 0 2
1 0 2
Where is that 3 coming from?
public static BigInteger simpleMultiply(BigInteger x, BigInteger y){
char [] longerNum;
char [] shorterNum;
if(x.compareTo(y)>=0){ // x is a longer/equal num
longerNum = x.toString().toCharArray();
shorterNum = y.toString().toCharArray();
}
else { //y is a longer num
longerNum = y.toString().toCharArray();
shorterNum = x.toString().toCharArray();
}
//shorter num equals the number of rows in partial result
// longer num + 1 equals the number of columns in partial result
int [][] partialResult = new int [shorterNum.length][longerNum.length+1];
int pastCarry=0;
int result=0;
int carry=0;
for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
{
int sInt = Integer.parseInt(""+shorterNum[sIndex]+"");
int lInt = Integer.parseInt(""+longerNum[lIndex]+"");
int product = sInt*lInt;
if (lIndex==0){
result = (pastCarry+product)% 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result; //one more column element in partialResult
partialResult[sIndex][lIndex] = carry;
}
else {
result = (pastCarry+product)% 10;
carry = (pastCarry+product) / 10;
pastCarry = carry;
partialResult [sIndex][lIndex+1] = result;//one more column element in partialResult
}
}
for (int i=0; i<partialResult.length;i++)
for (int j=0; j<partialResult[0].length;j++)
{
System.out.print(partialResult[i][j] + " ");
if (j==partialResult[0].length-1){System.out.println();}
}
return null;
}
It’s because you’re not zeroing out
pastCarrybetween iterations of the outer loop.Change
to
And by the way, the
int sInt = ....line should also be moved outside the inner loop since it doesn’t depend on anything inside the inner loop.