1 问题
有两个n位大整数XXX,YYY,它们数值之分大,如1e10001e10001e1000。现在要计算它们的乘积XYXYXY。
2 分析
2.1 传统方法
逐位相乘、错位相加,时间复杂度O(n2)O(n^2)O(n2)。效率太低。
2.2 分治方法
将n位的二进制整数X和Y各分为2段,每段的长为n/2位(为简单起见,假设n是2的幂)。此处整数用2进制表示。
X=a2n2+bY=c2n2+dX=a2^{\frac{n}{2}}+b\\ Y=c2^{\frac{n}{2}}+d X=a22n+bY=c22n+d
分治1
XY=ac2n+(ad+bc)2n2+bdXY=ac2^n+(ad+bc)2^{\frac{n}{2}}+bd XY=ac2n+(ad+bc)22n+bd
复杂度分析:
X乘Y,一共有4次n2\frac{n}{2}2n位大整数相乘,3次加法,2次移位。
这种分治的复杂度与传统计算方法相比并没有改进。
分治2
XY=ac2n+((a+b)(c+d)−ac−bd)2n2+bdXY=ac2^n+((a+b)(c+d)-ac-bd)2^{\frac{n}{2}}+bd XY=ac2n+((a+b)(c+d)−ac−bd)22n+bd
复杂度分析:
X乘Y,一共有3次n2\frac{n}{2}2n位大整数相乘,6次加法,2次移位。
相较于传统算法,这种分治算法的时间复杂度有较大的改进。
3 C++代码实现
#include <iostream>#include <cmath>#include <vector>using namespace std;#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; }
如果觉得《分治算法解大整数相乘问题》对你有帮助,请点赞、收藏,并留下你的观点哦!