算法分析与设计作业-大整数相乘-分治

算法作业-大整数相乘-分治

分 治 法 实 现 二 进 制 的 大 整 数 相 乘 。 分治法实现二进制的大整数相乘。

代码:

#include <bits/stdc++.h>
using namespace std;
template <typename T>
int toInt(T s)
{
	// 将字符串或字符转化为数字
	int res;
	stringstream ss;
	ss << s;
	ss >> res;
	return res;
}
string toStr(int n)
{
	// 将数字转为字符串
	string res;
	stringstream ss;
	ss << n;
	ss >> res;
	return res;
}
void addZero(string &s, int n, bool pre = true)
{
	// 在字符串前或者字符串后添加0(默认为前)
	string temp(n, '0');
	s = pre ? temp + s : s + temp;
}
void removeZero(string &s)
{
	// 去除前导零
	int i = 0;
	while (i < s.length() && s[i] == '0')
		++i;
	if (i < s.length())
		s = s.substr(i);
	else
		s = "0";
}

string add(string a, string b)
{
	// 大数加法(只考虑a+b非负)
	string res;
	removeZero(a);
	removeZero(b);
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	int l = max((int)a.size(), (int)b.size());
	for (int i = 0, j = 0; j || i < l; ++i)
	{
		int t = j;
		if (i < a.size())
			t += toInt(a[i]);
		if (i < b.size())
			t += toInt(b[i]);
		int q = t % 2;    ///2进制
		res = char(q + '0') + res;
		j = t / 2;        ///2进制
	}
	return res;
}
string sub(string a, string b)
{
	// 大数减法(只考虑a-b非负)
	string res;
	removeZero(a);
	removeZero(b);
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	int lx = (int)a.size(), ly = (int)b.size(), j = 0;
	//int* temp = new int[lx];
	int *temp = (int *)calloc(lx, sizeof(int));
	for (int i = 0; i < lx; ++i)
	{
		int ai = toInt(a[i]);
		int bi = i < ly ? toInt(b[i]) : 0;
		temp[j++] = ai - bi;
	}
	for (int i = 0; i < lx; ++i)
	{
		if (temp[i] < 0)
		{
			temp[i] += 2;    ///2进制
			--temp[i + 1];
		}
	}
	for (int i = lx - 1; i >= 0; --i)
	{
		res += toStr(temp[i]);
	}
	return res;
}
string mul(string a, string b)
{
	// 大数乘法(只考虑a,b非负)
	string res;
	int n = 2;
	if (a.size() > 2 || b.size() > 2)
	{
		n = 4;
		while (n < a.size() || n < b.size())
			n <<= 1;
		addZero(a, n - (int)a.size());
		addZero(b, n - (int)b.size());
	}
	if (a.size() == 1)
		addZero(a, 1);
	if (b.size() == 1)
		addZero(b, 1);
	if (n == 2)
	{ // 递归终止
		int temp = toInt(a) * toInt(b);
		res = toStr(temp);
	}
	else
	{
		string a1, a0, b1, b0, c2, c1, c0;
		a1 = a.substr(0, n / 2);
		a0 = a.substr(n / 2);
		b1 = b.substr(0, n / 2);
		b0 = b.substr(n / 2);
		c2 = mul(a1, b1);
		c0 = mul(a0, b0);
		c1 = sub(mul(add(a0, a1), add(b0, b1)), add(c2, c0));
		addZero(c2, n, false);
		addZero(c1, n / 2, false);
		res = add(add(c2, c1), c0);
	}
	return res;
}
int main()
{
    while(1){
	string a, b;
	cout<< "Input:" <<endl;

	cin >> a >> b;

    cout<< "Output:" << endl << mul(a, b) << endl << endl;
    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值