1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
| class Solution { public: const double PI = acos(-1.0);
struct Complex { double re, im;
Complex(double _re = 0.0, double _im = 0.0) { re = _re; im = _im; }
inline void real(const double &re) { this->re = re; }
inline double real() { return re; }
inline void imag(const double &im) { this->im = im; }
inline double imag() { return im; }
inline Complex operator-(const Complex &other) const { return Complex(re - other.re, im - other.im); }
inline Complex operator+(const Complex &other) const { return Complex(re + other.re, im + other.im); }
inline Complex operator*(const Complex &other) const { return Complex(re * other.re - im * other.im, re * other.im + im * other.re); }
inline void operator/(const double &div) { re /= div; im /= div; }
inline void operator*=(const Complex &other) { *this = Complex(re * other.re - im * other.im, re * other.im + im * other.re); }
inline void operator+=(const Complex &other) { this->re += other.re; this->im += other.im; }
inline Complex conjugate() { return Complex(re, -im); } };
vector<Complex> FFT(vector<Complex> &a, bool invert) { int n = a.size();
if (n == 1) { return a; }
vector<Complex> Pe(n / 2), Po(n / 2);
for (int i = 0; 2 * i < n; i++) { Pe[i] = a[2 * i]; Po[i] = a[2 * i + 1]; }
vector<Complex> ye = FFT(Pe, invert); vector<Complex> yo = FFT(Po, invert);
vector<Complex> y(n);
double ang = 2 * PI / n * (invert ? -1 : 1); Complex wn(cos(ang), sin(ang)); Complex w(1, 0);
for (int i = 0; i < n / 2; i++) { y[i] = ye[i] + w * yo[i]; y[i + n / 2] = ye[i] - w * yo[i]; w = w * wn; }
return y; }
string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") { return "0"; }
int len1 = num1.size(); int len2 = num2.size();
int n = 1; while (n < len1 + len2) { n = n << 1; }
vector<Complex> a(n); vector<Complex> b(n);
for (int i = len1 - 1; i >= 0; i--) { a[i] = Complex(num1[len1 - 1 - i] - '0', 0); }
for (int i = len2 - 1; i >= 0; i--) { b[i] = Complex(num2[len2 - 1 - i] - '0', 0); }
a = FFT(a, false); b = FFT(b, false);
for (int i = 0; i < n; i++) { a[i] = a[i] * b[i]; }
a = FFT(a, true);
string ans; int carry = 0; for (int i = 0; i < n; i++) { int sum = round(round(a[i].re) / n) + carry; carry = sum / 10; ans += sum % 10 + '0'; }
if (carry > 0) { ans += carry % 10 + '0'; }
int idx = ans.size() - 1; while (ans[idx] == '0' && idx > 0) { idx--; }
ans = ans.substr(0, idx + 1); reverse(ans.begin(), ans.end()); return ans; } }
|