FFT模板题。
C++FFT实现:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define ull unsigned long long
#define __ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
const int maxn = 5e5 + 10;
const ll mod = 1e9 + 7;
const ld PI = acos(-1.0);
#define cp complex<double>
int rev[maxn];
void FFT(cp *a, int n, int inv) {
int bit = 0;
while ((1 << bit) < n)++bit;
for (int i = 0; i <= n - 1; ++i) {
rev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (bit - 1));
if (i < rev[i])swap(a[i], a[rev[i]]);
}
for (int len = 2; len <= n; len <<= 1) {
int mid = len >> 1;
cp unit(cos(PI / mid), inv * sin(PI / mid));
for (int i = 0; i < n; i += len) {
cp omega(1, 0);
for (int j = 0; j < mid; ++j, omega *= unit) {
cp x = a[i + j], y = omega * a[i + j + mid];
a[i + j] = x + y;
a[i + j + mid] = x - y;
}
}
}
if (inv == -1) {
for (int i = 0; i <= n; ++i)a[i] /= n;
}
}
char a[maxn], b[maxn];
cp A[maxn], B[maxn];
int output[maxn];
int main() {
while (~scanf("%s%s", a, b)) {
int n = strlen(a);
int m = strlen(b);
for (int i = 0; i < n; ++i) {
A[i] = a[n - i - 1] - '0';
}
for (int i = 0; i < m; ++i) {
B[i] = b[m - i - 1] - '0';
}
int bitn = 1;
while (bitn < n + m)bitn <<= 1;
FFT(A, bitn, 1);
FFT(B, bitn, 1);
for (int i = 0; i < bitn; ++i) {
A[i] = A[i] * B[i];
}
FFT(A, bitn, -1);
for (int i = 0; i < bitn; ++i) {
output[i] += A[i].real() + 0.5;
output[i + 1] = output[i] / 10;
output[i] %= 10;
}
bool ok = 0;
for (int i = n + m; i >= 0; --i) {
if (ok || i == 0 || output[i]) {
printf("%d", output[i]);
ok = 1;
}
}
printf("\n");
memset(a, 0, sizeof a);
memset(b, 0, sizeof b);
memset(A, 0, sizeof A);
memset(B, 0, sizeof B);
memset(output, 0, sizeof output);
}
return 0;
}
本题用Java的大数类也能过。时间比C++长一些。
代码:
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
public class Main {
static BigInteger A, B;
public static void main(String[] args) throws IOException {
Scanner cin = new Scanner(System.in);
while (cin.hasNext()) {
A = cin.nextBigInteger();
B = cin.nextBigInteger();
System.out.println(A.multiply(B));
}
}
}