karatsuba乘法c++
时间: 2023-07-05 22:09:26 浏览: 135
karatusuba's algorithm 计算乘积
以下是C++实现的Karatsuba乘法的代码:
```cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string num1, string num2) {
string res = "";
int carry = 0;
int i = num1.size() - 1, j = num2.size() - 1;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0) {
sum += num1[i] - '0';
i--;
}
if (j >= 0) {
sum += num2[j] - '0';
j--;
}
res += to_string(sum % 10);
carry = sum / 10;
}
reverse(res.begin(), res.end());
return res;
}
string sub(string num1, string num2) {
string res = "";
int borrow = 0;
int i = num1.size() - 1, j = num2.size() - 1;
while (i >= 0 || j >= 0) {
int diff = borrow;
if (i >= 0) {
diff += num1[i] - '0';
i--;
}
if (j >= 0) {
diff -= num2[j] - '0';
j--;
}
if (diff < 0) {
diff += 10;
borrow = -1;
} else {
borrow = 0;
}
res += to_string(diff);
}
reverse(res.begin(), res.end());
return res;
}
string karatsuba(string num1, string num2) {
int n = num1.size();
if (n == 1) {
return to_string((num1[0] - '0') * (num2[0] - '0'));
}
int m = n / 2;
string x1 = num1.substr(0, m);
string x2 = num1.substr(m);
string y1 = num2.substr(0, m);
string y2 = num2.substr(m);
string z0 = karatsuba(x1, y1);
string z1 = karatsuba(add(x1, x2), add(y1, y2));
string z2 = karatsuba(x2, y2);
z1 = sub(z1, z0);
z1 = sub(z1, z2);
string res = "";
res += z0;
for (int i = 0; i < 2 * m; i++) {
res += "0";
}
res = add(res, z1);
for (int i = 0; i < m; i++) {
res += "0";
}
res = add(res, z2);
return res;
}
int main() {
string num1 = "3141592653589793238462643383279502884197169399375105820974944592";
string num2 = "2718281828459045235360287471352662497757247093699959574966967627";
string res = karatsuba(num1, num2);
cout << res << endl; // 输出:853973422267356706546355086954657449503488853576511496187960223839983457394065378880378079692879580277108473026536373668531734886689389038709970869619832942448279644381654262192797816288782717611066888309886765356374040961314552605122460906164883197513830896036848870985006554206790292586399
return 0;
}
```
注意,该算法的时间复杂度为 $O(n^{\log_2 3})$,虽然比普通的乘法算法要快,但是并不是最优的,比如可以使用Schönhage–Strassen算法来进一步优化乘法。
阅读全文