Debugging 帮助调试这个乘法算法

Debugging 帮助调试这个乘法算法,debugging,Debugging,我正在实现将其性能与分而治之的方法进行比较 我放弃了用字节算术做这件事的最初想法,选择了通过字符数组转换数字 好吧,在33 x 33这样的简单情况下,一切都可以正常工作,调试方法正确地打印出来: 0 9 9 0 9 9 然而,在34 x 33上,我得到了 1 0 3 1 0 2 它应该在哪里 1 0 2 1 0 2 那3是从哪里来的 public static BigInteger simpleMultiply(BigInteger x, BigInteger y){ char

我正在实现将其性能与分而治之的方法进行比较

我放弃了用字节算术做这件事的最初想法,选择了通过字符数组转换数字

好吧,在33 x 33这样的简单情况下,一切都可以正常工作,调试方法正确地打印出来:

0 9 9
0 9 9
然而,在34 x 33上,我得到了

1 0 3
1 0 2
它应该在哪里

1 0 2
1 0 2
那3是从哪里来的

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;
 }

这是因为您并没有在外循环的迭代之间将pastCarry归零

改变

for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
    for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
    {
        [snip]
    }

顺便说一下,int sInt=。。。。行也应该移到内部循环之外,因为它不依赖于内部循环中的任何内容

for (int sIndex=(shorterNum.length-1); sIndex>=0; sIndex--)
{
    pastCarry = 0;
    for (int lIndex = (longerNum.length-1); lIndex>=0; lIndex--)
    {
        [snip]
    }
}