大整数乘法运算

乘法的计算比加法要麻烦,主要有两个思路:

  1. 模拟手算
  2. 先不管所有进位计算,最后统一处理进位

乘法手算的步骤:

还是用string来表示数字,乘积的位数最大为两个相乘数的位数和,所以开始就可给定结果的位数。为了节省内存,我们用了一个小技巧:用result来表示每次相乘的和,这样就不需额外声明保存每位乘积的变量了。

具体代码:

std::string Mul(std::string a, std::string b)
{
	std::string result(a.length() + b.length(), '0');  //两个数相乘,结果的位数不会超过它们的位数之和。

	for (int i = b.length() - 1; i >= 0; --i)
	{
		int mul_carry = 0, add_carry = 0;  //记录乘法时的进位,加法时的进位
		for (int j = a.length() - 1; j >= 0; --j)
		{
			int temp = (b[i] - '0') * (a[j] - '0') + mul_carry;  //每位相乘的值
			mul_carry = temp / 10;  //记录进位
			temp %= 10;  //进位后的值

			int temp2 = result[i + j + 1] - '0' + temp + add_carry;
			result[i + j + 1] = temp2 % 10 + 48;  //设置相应位上的值和原本位上值相加后的值。
			add_carry = temp2 / 10;  //记录进位
		}
		result[i] += mul_carry + add_carry;
	}

	//如果首位是0,则从第二位开始输出
	if (result[0] == '0')
		result = result.substr(1, result.length());

	return result;
}

现在来看看它的威力:

posted @ 2018-07-22 13:26  cpluspluser  阅读(2595)  评论(0编辑  收藏  举报