A * B Problem Plus
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 18312 Accepted Submission(s): 4106
Problem Description
Calculate A * B.
Input
Each line will contain two integers A and B. Process to end of file.
Note: the length of each integer will not exceed 50000.
Note: the length of each integer will not exceed 50000.
Output
For each case, output A * B in one line.
Sample Input
1
2
1000
2
Sample Output
2
2000
题目大意:
给定两个大整数,求 A∗B 的值。
吐槽:
其实这个题目完全可以用 Java 做,但是为了训练 FFT ,建议还是用 C 写一发。
解题思路:
因为大整数的位数太大啦,如果暴力算的话肯定会超时,所以我们要用到一种加速方法
My Code:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const double PI = acos(-1.0);
typedef long long LL;
const LL MAXN = 2e5+5;
struct complex {
double a, b;
complex(double aa = 0.0, double bb = 0.0) { a = aa; b = bb; }
complex operator +(const complex &e) { return complex(a + e.a, b + e.b); }
complex operator -(const complex &e) { return complex(a - e.a, b - e.b); }
complex operator *(const complex &e) { return complex(a * e.a - b * e.b, a * e.b + b * e.a); }
}x1[MAXN], x2[MAXN], x[MAXN];
void change(complex * y, LL len) {
LL i, j, k;
for (i = 1, j = len / 2; i < len - 1; i++) {
if (i < j) swap(y[i], y[j]);
k = len / 2;
while (j >= k) {
j -= k;
k /= 2;
}
if (j < k) j += k;
}
}
void fft(complex *y, LL len, LL on) {
change(y, len);
for (LL h = 2; h <= len; h <<= 1) {
complex wn(cos(-on * 2 * PI / h), sin(-on * 2 * PI / h));
for (LL j = 0; j < len; j += h) {
complex w(1, 0);
for (LL k = j; k < j + h / 2; k++) {
complex u = y[k];
complex t = w * y[k + h / 2];
y[k] = u + t;
y[k + h / 2] = u - t;
w = w * wn;
}
}
}
if (on == -1)
for (LL i = 0; i < len; i++)
y[i].a /= len;
}
char A[MAXN], B[MAXN];
LL f[MAXN], g[MAXN];
LL ans[MAXN];
int main()
{
while(~scanf("%s%s",A,B))
{
LL len = 1LL;
LL len1 = strlen(A);
LL len2 = strlen(B);
memset(f, 0, sizeof(f));
memset(g, 0, sizeof(g));
for(LL i=0; i<len1; i++)
f[i] = (A[i]-'0');
for(LL i=0; i<len2; i++)
g[i] = (B[i]-'0');
while(len<2*len1 || len<2*len2)len<<=1LL;
///cout<<len<<endl;
for(LL i=0; i<len1; i++)
x1[len1-i-1].a = f[i], x1[i].b = 0;
for(LL i=len1; i<len; i++)
x1[i].a = 0, x1[i].b = 0;
for(LL i=0; i<len2; i++)
x2[len2-1-i].a = g[i], x2[i].b = 0;
for(LL i=len2; i<len; i++)
x2[i].a = 0, x2[i].b = 0;
fft(x1, len, 1), fft(x2, len, 1);
for(LL i=0; i<len; i++)
x[i] = x1[i] * x2[i];
fft(x, len, -1);
memset(ans, 0, sizeof(ans));
for(LL i=0; i<len; i++)
ans[i] = (LL)(x[i].a+0.5);
for(LL i=0; i<len; i++){
ans[i+1] += ans[i] / 10;
ans[i] %= 10;
}
LL tmp = 0;
for(LL i=len-1; i>=0; i--)
if(ans[i]){
tmp = i;
break;
}
for(LL i=tmp; i>=0; i--)
putchar(ans[i]+'0');///(输出加速)
puts("");
}
return 0;
}