1 问题
有两个n位大整数
2 分析
2.1 传统方法
逐位相乘、错位相加,时间复杂度
2.2 分治方法
将n位的二进制整数X和Y各分为2段,每段的长为n/2位(为简单起见,假设n是2的幂)。此处整数用2进制表示。
![52aa1ed2570da6970c211650fac7d93f.png](https://img-blog.csdnimg.cn/img_convert/52aa1ed2570da6970c211650fac7d93f.png)
- 分治1
复杂度分析:
X乘Y,一共有4次
![9d15c76ca08ebf44e63ce69b435e1629.png](https://img-blog.csdnimg.cn/img_convert/9d15c76ca08ebf44e63ce69b435e1629.png)
![880f84901c1016f0fdde10ea8adc287b.png](https://img-blog.csdnimg.cn/img_convert/880f84901c1016f0fdde10ea8adc287b.png)
这种分治的复杂度与传统计算方法相比并没有改进。
- 分治2
复杂度分析:
X乘Y,一共有3次
![5c6573cc5da56f71ce558ed214659d84.png](https://img-blog.csdnimg.cn/img_convert/5c6573cc5da56f71ce558ed214659d84.png)
![47f024c86f39869b71c195b1cbc35abd.png](https://img-blog.csdnimg.cn/img_convert/47f024c86f39869b71c195b1cbc35abd.png)
相较于传统算法,这种分治算法的时间复杂度有较大的改进。
3 C++代码实现
#include <iostream>
#include <cmath>
#include <vector>
#define SIGN(A) ((A > 0) ? 1 : -1)
int IntegerMultiply(int X, int Y, int N){
int sign = SIGN(X) * SIGN(Y);
int x = abs(X);
int y = abs(Y);
if((0 == x) || (0 == y))
return 0;
if (1 == N)
return x*y;
else{
int XL = x / (int)pow(10., (int)N/2);
int XR = x - XL * (int)pow(10., N/2);
int YL = y / (int)pow(10., (int)N/2);
int YR = y - YL * (int)pow(10., N/2);
int XLYL = IntegerMultiply(XL, YL, N/2);
int XRYR = IntegerMultiply(XR, YR, N/2);
int XLYRXRYL = IntegerMultiply(XL - XR, YR - YL, N/2) + XLYL + XRYR;
return sign * (XLYL * (int)pow(10., N) + XLYRXRYL * (int)pow(10., N/2) + XRYR);
}
}
void test2(void){
int x = 1234;
int y = 4321;
cout<<"x * y = "<<IntegerMultiply(x, y, 4)<<endl;
cout<<"x * y = "<<x*y<<endl;
}