我正在尝试实现递归 Karatsuba 算法以将两个多项式(相同程度)相乘。我的代码仍然不适用于度数大于 1 的多项式。谁能向我解释我在函数中做错了什么?它应该适用于偶数和奇数个系数。
多项式存储在一个数组中long
。每个元素代表一个系数,因此1 2 3 4
表示1 + 2x + 3x^2 + 4x^3
和参数size
是系数的数量。
long* karatsuba(const long *A, const long *B, int size) {
long *lowA, *highA, *lowB, *highB, *midA, *midB;
if (size == 1)
return naive(A, B, size, size);
int half = size / 2;
lowA = new long[half];
lowB = new long[half];
midA = new long[half];
midB = new long[half];
highA = new long[half];
highB = new long[half];
// init low coefficients
for(int i=0; i<half; i++){
lowA[i] = A[i];
lowB[i] = B[i];
}
// init high // init low coefficients
for(int i=half; i<size; i++){
highA[i-half] = A[i];
highB[i-half] = B[i];
}
// init mid // init low coefficients
for(int i=0; i<half; i++){
midA[i] = lowA[i] + highA[i];
midB[i] = lowB[i] + highB[i];
}
long *z0 = karatsuba(lowA, lowB, half);
long *z1 = karatsuba(midA, midB, half);
long *z2 = karatsuba(highA, highB, half);
// compute the result
long *result = new long[2*size-1];
for(int i=0; i<half; i++){
result[i + 2*half] = z2[i];
result[i + half] = z1[i] - z0[i] - z2[i];
result[i] = z0[i];
}
return result;
}
我的主要问题是这个函数不能计算正确的结果。