高精度乘法模板(fft)

 正常高精度复杂度是o(n^2),fft复杂度o(nlogn)

#define int long long//__int128 2^127-1(GCC)
#define PII pair<int,int>
#define f first
#define s second
using namespace std;
const int inf = 0x3f3f3f3f3f3f3f3f, N = 3e5 + 5, mod = 1e9 + 7;
const double PI = acos(-1);
int n, m;
struct Complex
{
    double x, y;
    Complex operator+ (const Complex& t) const
    {
        return { x + t.x, y + t.y };
    }
    Complex operator- (const Complex& t) const
    {
        return { x - t.x, y - t.y };
    }
    Complex operator* (const Complex& t) const
    {
        return { x * t.x - y * t.y, x * t.y + y * t.x };
    }
}a[N], b[N];

int rev[N], bit, tot;
void fft(Complex a[], int inv)
{
    for (int i = 0; i < tot; i++)
        if (i < rev[i])
            swap(a[i], a[rev[i]]);
    for (int mid = 1; mid < tot; mid <<= 1)
    {
        auto w1 = Complex({ cos(PI / mid), inv * sin(PI / mid) });
        for (int i = 0; i < tot; i += mid * 2)
        {
            auto wk = Complex({ 1, 0 });
            for (int j = 0; j < mid; j++, wk = wk * w1)
            {
                auto x = a[i + j], y = wk * a[i + j + mid];
                a[i + j] = x + y, a[i + j + mid] = x - y;
            }
        }
    }
}
signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    string aa, bb;
    cin >> aa >> bb;
    n = aa.size()-1, m = bb.size()-1;
    for (int i = 0; i <= n; i++) { a[i].x = aa[i] - '0'; }
    for (int i = 0; i <= m; i++) { b[i].x = bb[i] - '0'; }
    while ((1 << bit) < n + m + 1) bit++;
    tot = 1 << bit;
    for (int i = 0; i < tot; i++) {
        rev[i] = (rev[i >> 1] >> 1) | ((i & 1) << (bit - 1));
    }
    fft(a, 1), fft(b, 1);
    for (int i = 0; i < tot; i++) a[i] = a[i] * b[i];
    fft(a, -1);
    string s;
    int t=0;
    for (int i = n+m; i >= 0; i--) {
        t+=(int)(a[i].x / tot + 0.5);
        s+=t%10+'0';
        t/=10;
    }
    if(t) s+=t+'0';
    reverse(s.begin(),s.end());
    cout<<s;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值