大整数乘法的算法能将两个二进制数相乘的时间复杂度由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,所以数据范围不大,想要输入输出大的数据需要自行切换数据类型。