BigInt乘法w/int数组

BigInt Multiplication w/ int arrays

本文关键字:int 数组 乘法 BigInt      更新时间:2023-10-16

我正在用C++制作一个BigInt类作为练习。我目前正在研究乘法功能。我的BigInt表示为一个固定长度(非常大)的int[],每个条目都是输入数字的一位数字。

因此,BigInt = 324将导致[0,0,0,..,3,2,4]

我目前正在尝试使用以下代码进行乘法运算:

// multiplication
BigInt BigInt::operator*(BigInt const& other) const {
  BigInt a = *this;
  BigInt b = other;
  cout << a << b << endl;
  BigInt product = 0;
  for(int i = 0; i < arraySize; i++){
    int carry = 0;
    for(int j = 0; j < arraySize; j++){
      product.digits[arraySize - (j + i)] += (carry + (a.digits[j] * b.digits[i]));
      carry = (product.digits[arraySize - (j + i)] / 10);
      product.digits[arraySize - (j + i)] = (product.digits[arraySize - (j + i)] % 10);
    }
    product.digits[arraySize - i] += carry;
  }
  return product;
}

我的答案一直返回0。例如,2 * 2 = 0

不确定这是否会修复您的程序,但您有Undefined Behavior,因为它:

product.digits[arraySize - (j + i)]

i + j > arraySize时,这个索引arraySize - (j + i)变为负值,这显然会发生在循环中。

基本上,当两个数字乘以n个数字时,结果可能宽至2n个数字。由于您将所有数字编码在固定长度的arraySize上,因此必须采取措施避免越界。

if(i+j) <= arraySize可以做一个简单的测试,或者通过改变第二个循环:

 for(int j = 0; j < arraySize - i; j++)

或者,最好使用std::vector作为BigInt的内部表示。它可以动态调整大小以预先适应您的结果。

目前还不能完全确定这是否会完全修复您的代码,但在继续调试之前,必须先修复它。删除UB后会更容易。在这里,我赞同@Dúthomhas的注意,即您对数组的索引似乎明显不规则。。。结果从右到左,输入从左到右。。。