分块计算大数乘法

 

1234*5678 =   12 | 34
            x 56 | 78  =====> 34*78 + 12*78*100 + 34*56*100 + 12*56*10000     
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

void add2res(string &res, const string &str1)
{
	int flag = 0; //进位标志
	size_t i, j;
	for (i = res.length(), j = str1.length(); i != 0, j != 0; i--, j--)
	{
		int x = res[i-1] - '0' + str1[j-1] - '0' + flag;
		if (x > 9){
			res[i-1] = x % 10 + '0';
			flag = 1;
		}
		else{
			res[i - 1] = x + '0';
			flag = 0;
		}
	}
	if (flag){
		for (; i > 0 && flag; i--){
			int x = res[i - 1] - '0' + flag;
			if (x > 9){
				res[i - 1] = x % 10 + '0';
				flag = 1;
			}
			else{
				res[i - 1] = x + '0';
				flag = 0;
			}
		}
	}
}

string mul(string bignum1, string bignum2)
{
	//将bignum1和bignum2修改为长度为8的倍数,前面添加‘0’字符,是为了后面的分块计算方便
	size_t len = bignum1.length() > bignum2.length() ? bignum1.length() : bignum2.length();
	if (len % 8 != 0)
		len = (len / 8 + 1) * 8;
	string res(2*len + 1, '0');
	for (size_t i = bignum1.length(); i < len; i++)
		bignum1 = '0' + bignum1;
	for (size_t i = bignum2.length(); i < len; i++)
		bignum2 = '0' + bignum2;

	int blocks = len / 8;
	unsigned long long product; //测试环境的long是32位的,如果long为64位,可以使用单long

	//将bignum1和bignum2分成几块,分别计算各块的乘积,可以直接使用系统的乘法运算
	for (int i = 0; i < blocks; i++)
	{
		string s1 = bignum1.substr(len-8*i-8, 8);
		unsigned long long tmp1 = atoi(s1.c_str());
		for (int j = 0; j < blocks; j++)
		{
			string s2 = bignum2.substr(len - 8 * j - 8, 8);
			unsigned long long tmp2 = atoi(s2.c_str());
			product = tmp1 * tmp2;
			stringstream stream;
			string str1;
			stream << product;
			stream >> str1;
			for (int k = 0; k < (i + j) * 8; k++)
				str1 += '0';
			add2res(res, str1);
		}
	}
	//去掉前面的0
	for (string::iterator iter = res.begin();
		iter != res.end(); ++iter)
	{
		if (*iter != '0'){
			if (iter != res.begin())
				res.erase(res.begin(), iter);
			break;
		}
	}
	return res;
}

int main()
{
	string bignum1;
	string bignum2;
	cout << "Please input num1: ";
	cin >> bignum1;
	cout << endl;
	cout << "Please input num2: ";
	cin >> bignum2;
	cout << endl << "num1 * num2 = ";

	string res = mul(bignum1, bignum2);
	cout << res << endl;

	getchar();
	getchar();

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值