c++ - 大整数乘法

标签 c++ biginteger

大家好我一直在研究一个大整数类,我已经完成了加法和减法,现在我正在尝试编写一个有效的乘法函数,但是如果我在前 3 位数字之后乘以一个非常大的数字,它会失去精度答案是错误的。任何人都可以帮助我解决我在这里做错的事情我想不出任何东西吗?

BigInt operator*(const BigInt& left, const BigInt& right)
{
    BigInt temp1 = left;
    BigInt temp2 = right;
    temp1.sign = 1;
    temp2.sign = 1;
    BigInt Max = MAX(temp1, temp2), Min = MIN(temp1, temp2);
    ArrayList<char> temp_container = ArrayList<char>();
    ArrayList<BigInt> nums = ArrayList<BigInt>();
    int carry = 0;
    int zero_count = 0;

    for (int i = Min.Digits.size() - 1; i > -1; i--)
    {
        for (int j = Max.Digits.size() - 1; j > -1; j--)
        {
            int temp = (Max.Digits.get(j) * Min.Digits.get(i)) + carry;//Multiply Digits

            if (temp < 10)//if it is a digit
            {
                temp_container.add_to_front(temp + '0');
                carry = 0;
            }
            //else if it isnt a digit
            else if (temp >= 10 && j > 0)
            {
                temp_container.add_to_front((temp / 10) + '0');
                carry = temp % 10;
            }
            else if (temp >= 10 && j < 0)
            {
                temp_container.add_to_front((temp / 10) + '0');
                temp_container.add_to_front((temp % 10) + '0');

            }
        }

        for (int j = 0; j < zero_count; j++)
        {
            temp_container.add('0');
        }
        nums.add(BigInt(temp_container));
        temp_container.removeAll();
        zero_count++;//increase the amount of zeros to add to the next number
    }


    BigInt result = BigInt("0");
    for (int i = 0; i < nums.size(); i++)
    {
        result += nums.get(i);//add all of the number up
    }
    //determine if positive or negative
    if (left.sign == right.sign)
    {
        result.sign = 1;
    }
    else
    {
        result.sign = -1;
    }
    return result;
}

最佳答案

你的进位和你的数字相反(当有进位时)。

关于c++ - 大整数乘法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576267/

相关文章:

algorithm - 使用分治法的整数乘法算法?

java - 循环添加 BigInteger java

c++ - OpenCV - SURF 特征比较

c++ - SVML 与普通内在平方根函数之间有区别吗?

java - 计算阶乘n的时间复杂度是多少!使用 Java 的 BigInteger

java - BigInteger::intValueExact() - 这有什么意义?

c++ - deque 是如何管理内存的?

c++ - 如何解析 POST body/GET 参数?

java - Java中如何获取BigInteger的精度