c++算法分析与设计之大整数递归乘法详解

大整数乘法的算法能将两个二进制数相乘的时间复杂度由O(n²)降为O(n1.59),还是比较厉害的一个算法。下面看一下我的实现过程。

#include<iostream>
#include<cmath>
using namespace std;
int powf(int a, int b)//自定义的求次方函数,因为在c++中有类型限制,使用不方便
{
	int t = 1;
	for (int i = 1; i <= b; i++)
		t = t * a;
	return t;
}
int add(int a, int b)//a,b是两个二进制数,输出两者的二进制之和
{
	int t = a + b;
	int cnt = 1;
	while (t / 10 != 0)
	{
		cnt++;
		t /= 10;
	}
	t = a + b;
	for (int i = 1; i <= cnt; i++)
	{
		int temp = t % powf(10, i) / powf(10, i - 1);
		if (temp > 1)
			t = t + 8 * powf(10, i - 1);
	}
	return t;
}
int multi(int a, int b)//a,b是两个二进制数,输出两者的二进制乘积(用计算机组成原理中计算机计算的方法)
{
	int cnt = 1;
	int sum = 0;
	int yt = b;
	while (yt / 10 != 0)
	{
		cnt++;
		yt /= 10;
	}
	yt = b;
	for (int i = 1; i <= cnt; i++)
	{
		int temp = yt % powf(10, i) / powf(10, i - 1);
		if (temp == 1)
			sum = add(sum, a*powf(10, i - 1));
	}
	return sum;
}
int sup(int a, int b)//求两者二进制差的绝对值
{
	int temp = a - b;
	int cnt = 1;
	int result = 0;
	int r = a - b;
	if (temp == 0)
		return 0;
	else
	{
		while (temp / 10 != 0)
		{
			cnt++;
			temp /= 10;
		}
		int *p = (int *)malloc(cnt * sizeof(int));
		for (int i = 0; i < cnt; i++)
		{
			if (r % 10 >= 8)
				p[i] = r % 10 - 8;
			else p[i] = r % 10;
			r /= 10;
		}
		for (int i = 0; i < cnt; i++)
		{
			result = p[i] * powf(10, i) + result;
		}
	}
	return fabs(result);
}
int the_core_function(int x, int y)//核心递归函数
{
	int n = 1;
	int a, b, c, d;
	int temp = x;
	while (temp / 10 != 0)
	{
		n++;
		temp /= 10;
	}
	if (n == 1)
	{
		return x * y;
	}
	else
	{
		a = x / powf(10, n / 2);
		b = x % powf(10, n / 2);
		c = y / powf(10, n / 2);
		d = y % powf(10, n / 2);
		return add(add(the_core_function(a, c)*powf(10, n), add(add(the_core_function(sup(a, b), sup(d, c)), the_core_function(a, c)), the_core_function(b, d))*powf(10, n / 2)), the_core_function(b, d));
	}
}
int main()
{
	int x, y;
	cin >> x >> y;
	cout << the_core_function(x, y);
}

在设计过程的还是遇到了很多问题的,因为要求输入输出都是二进制,还不能使用转化为十进制得出结果后再转换回来的方法(因为是模拟计算机计算的),顺便借这个题用十进制来模拟二进制的输入输出,和中间的加减乘的进制转换,琢磨了不短的时间。这个程序用的是int,所以数据范围不大,想要输入输出大的数据需要自行切换数据类型。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值