计算A * B
A,B 长度均不超过50000.
input
1
2
1000
2
output
2
2000
solution
将A, B 分别看作一个多项式,进行多项式乘法,最后考虑进位问题
code
//Siberian Squirrel
//#include<bits/stdc++.h>
#include<unordered_map>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cmath>
#define ACM_LOCAL
using namespace std;
typedef long long ll;
const double PI = acos(-1);
const double eps = 1e-7;
const int MOD = 3221225473;
const int N = 5e6 + 10;
struct Complex {
double x, y;
Complex(double _x, double _y) :x(_x), y(_y) {}
Complex() {}
Complex operator + (const Complex & c) {
return Complex(x + c.x, y + c.y);
}
Complex operator - (const Complex &c) {
return Complex(x - c.x, y - c.y);
}
Complex operator * (const Complex &c) {
return Complex(x * c.x - y * c.y, x * c.y + y * c.x);
}
} A[N], a[N], b[N];
int rev(int id, int len) {
int ret = 0;
for(int i = 0; (1 << i) < len; i++) {
ret <<= 1;
if(id & (1 << i)) ret |= 1;
}
return ret;
}
inline void FFT(Complex* a, int len, int DFT) {
for(int i = 0; i < len; i++)
A[rev(i, len)] = a[i];
for(int s = 1; (1 << s) <= len; s++) {
int m = (1 << s);
Complex wm = Complex(cos(DFT*2*PI/m), sin(DFT*2*PI/m));
for(int k = 0; k < len; k += m) {
Complex w = Complex(1, 0);
for(int j = 0; j < (m >> 1); j++) {
Complex t = w * A[k + j + (m >> 1)];
Complex u = A[k + j];
A[k + j] = u + t;
A[k + j + (m >> 1)] = u - t;
w = w * wm;
}
}
}
if(DFT == -1) for(int i = 0; i < len; i++) A[i].x /= len, A[i].y /= len;
for(int i = 0; i < len; i++) a[i] = A[i];
return;
}
inline void Conv(int len){
FFT(a, len, 1);
FFT(b, len, 1);
for(int i = 0; i < len; i++)
a[i] = a[i] * b[i];
FFT(a, len, -1);
}
char A_s[50010], B_s[50010];
int ans[N];
int A_len, B_len, A_pos, B_pos;
inline void solve() {
A_len = strlen(A_s);
B_len = strlen(B_s);
A_pos = B_pos = 0;
while((1 << A_pos) < A_len) ++ A_pos;
while((1 << B_pos) < B_len) ++ B_pos;
int len = (1 << (max(A_pos, B_pos) + 1));
for(int i = 0; i < len; i++) {
if(i < A_len) a[i] = Complex(A_s[A_len - i - 1] - '0', 0);
else a[i] = Complex(0, 0);
if(i < B_len) b[i] = Complex(B_s[B_len - i - 1] - '0', 0);
else b[i] = Complex(0, 0);
}
Conv(len);
for(int i = 0; i < len; i++)
ans[i] = (int)(a[i].x + 0.5);
for(int i = 0; i < len - 1; i++) {
ans[i + 1] += ans[i] / 10;
ans[i] %= 10;
}
bool f = false;
for(int i = len - 1; i >= 0; i--) {
if(ans[i]) printf("%d", ans[i]), f = true;
else if(f || i == 0) printf("0");
}
puts("");
}
int main() {
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
#endif
int o = 1;
// scanf("%d", &o);
while(o --) {
while(~scanf("%s", A_s)) {
scanf("%s", B_s);
solve();
}
}
return 0;
}