A*B problem(FFT)

A*B problem(FFT)

Set two polynomials \(A(x)\) and \(B(x)\) , their coefficients are mirrored and reversed, and the resulting polynomials are \(A'(x)\) and \(B'(x )\) . Then the coefficients of \(C(x)=A(x)*B(x)\) and \(C'(x)=A'(x)*B'(x)\) are also mirror-reversed. This, let's understand it emotionally.

0.0

So it's easy to do it the other way around. Since it is a multiplication of large integers, it is enough to carry one digit from the one digit to the highest digit after the calculation. Note that the array is quadrupled!

#include <cmath>
#include <cctype>
#include <cstdio>
using namespace std;

const int maxn=6e4+5;
const double pi=3.1415926535898;

struct Cpx{
    double x, y;
    Cpx (double t1=0, double t2=0){ x=t1, y=t2; }
}A[maxn*4], B[maxn*4], C[maxn*4];
Cpx operator +(Cpx &a, Cpx &b){ return Cpx(a.x+b.x, a.y+b.y); }
Cpx operator -(Cpx &a, Cpx &b){ return Cpx(a.x-b.x, a.y-b.y); }
Cpx operator *(Cpx &a, Cpx &b){ return Cpx(a.x*b.x-a.y*b.y, a.x*b.y+a.y*b.x); }
void swap(Cpx &x, Cpx &y){ Cpx t=x; x=y; y=t; }

int n, r[maxn*4], limit=1, l, ans[maxn*4];  //这里也要乘4!

void fdft(Cpx *a, int n, int flag){
    for (int i=0; i<n; ++i) if (i<r[i]) swap(a[i], a[r[i]]);
    for (int mlen=1; mlen<n; mlen<<=1){
        Cpx w1(cos(pi/mlen), flag*sin(pi/mlen)), x, y;
        for (int i=0; i<n; i+=(mlen<<1)){  //起点
            Cpx w(1, 0);
            for (int j=i; j<i+mlen; ++j, w=w*w1){  //遍历区间系数转点值
                x=a[j], y=w*a[j+mlen];
                a[j]=x+y; a[j+mlen]=x-y; }
        }
    }
}

int main(){
    scanf("%d", &n);  //倒着存方便补零 两个n-1次的多项式
    char c; while (!isdigit(c=getchar()));
    for (int i=0; i<n; ++i, c=getchar()) A[n-i-1].x=c-48;
    while (!isdigit(c=getchar()));
    for (int i=0; i<n; ++i, c=getchar()) B[n-i-1].x=c-48;
    while (limit<=2*n-2) limit<<=1, ++l;  //需要2×n-2个点,但是有2×n-1个系数
    for (int i=1; i<limit; ++i)
        r[i]=(r[i>>1]>>1)+((i&1)<<(l-1));  //1<<r就是倒数第r+1位
    fdft(A, limit, 1); fdft(B, limit, 1);
    for (int i=0; i<limit; ++i) C[i]=A[i]*B[i];
    fdft(C, limit, -1);
    for (int i=0; i<limit; ++i) ans[i]+=+C[i].x/limit+0.5;
    for (int i=0; i<limit; ++i)
        ans[i+1]+=ans[i]/10, ans[i]%=10;
    bool flag=false;
    for (int i=limit; i>=0; --i){
        if (ans[i]>0) flag=true;
        if (flag) printf("%d", ans[i]);
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325300120&siteId=291194637
FFT