【BZOJ2179】FFT快速傅立叶 高精度乘模板题

广告:

#include <stdio.h>
int main()
{
    puts("转载请注明出处[vmurder]谢谢");
    puts("网址:blog.csdn.net/vmurder/article/details/44015679");
}

题解:

其实没什么题解,只是贴个模板+理解注释

代码:

#include <cmath>
#include <cstdio>
#include <cstring>
#include <complex>
#include <iostream>
#include <algorithm>
using namespace std;
#define N 131075

int n,c[N];
complex<double> a[N],b[N],p[N];
const double pi=acos(-1);

void FFT(complex<double> x[],int n,int type)
{
    int i,j,k,t;
    /* 按二进制位翻转: 比如01234567 -> 04261537 000 000 001 100 010 010 011 110 100 001 101 101 110 011 111 111 */
    for(i=0,t=0;i<n;i++) // 按位翻转
    {
        if(i>t) swap(x[i],x[t]);
        for(j=n>>1;(t^=j)<j;j>>=1);
    }
    // 对于 wn
    // type== 1 时 复平面上正向旋转单位角度
    // type==-1 时 复平面上负向旋转单位角度
    for(k=2;k<=n;k<<=1) 
    {
        complex<double> wn(cos(type*2*pi/k),sin(type*2*pi/k));
        for(i=0;i<n;i+=k)
        {
            complex<double> w(1,0),t; // 可以直接写w = 1 , x轴是实部,y轴是虚部。
            for(j=0;j<k>>1;w*=wn,j++)
                t=w*x[i+j+(k>>1)],
                x[i+j+(k>>1)]=x[i+j]-t, x[i+j]+=t;
        }
    }
}

int main()
{
    int i,j,k;
    cin>>n;
    for(getchar(),i=n-1;i>=0;i--)a[i]=getchar()-'0';
    for(getchar(),i=n-1;i>=0;i--)b[i]=getchar()-'0';
    for(j=n,i=1;i>>2<j;i<<=1)n=i;
    FFT(a,n,1),FFT(b,n,1); // 转化过去
    for(i=0;i<n;i++) p[i]=a[i]*b[i];
    FFT(p,n,-1); // 转化回来

    int len=0; // 输出
    for(i=0;i<n;i++)
        c[i]=p[i].real()/n+0.1; // eps=0.1
    for(i=0;i<n;i++)
        if(c[i]) len=i, c[i+1]+=c[i]/10, c[i]%=10;
    for(i=len;i>=0;i--)
        printf("%d",c[i]);
    return 0;
}

你可能感兴趣的:(模板,高精度,fft,BZOJ2179)