POJ 2389 Bull Math(FFT)

Description
给出两个数A和B,求A*B
Input
两个数字串,串长均不超过40
Output
输出两个串所表示数字的乘积
Sample Input
11111111111111
1111111111
Sample Output
12345679011110987654321
Solution
可以直接暴力模拟高精度乘法,也可以用FFT加速
Code

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
#define maxn 111
typedef long long ll;
#define PI acos(-1.0) 
struct complex
{
    double r,i;
    complex(double _r=0,double _i=0)
    {
        r=_r,i=_i;
    }
    complex operator +(const complex &b)
    {
        return complex(r+b.r,i+b.i);
    }
    complex operator -(const complex &b)
    {
        return complex(r-b.r,i-b.i);
    }
    complex operator *(const complex &b)
    {
        return complex(r*b.r-i*b.i,r*b.i+i*b.r);
    }
};
void change(complex *x,int len)
{
    for(int i=1,j=len/2;i<len-1;i++)
    {
        if(i<j)swap(x[i],x[j]);
        int k=len/2;
        while(j>=k)
        {
            j-=k;
            k/=2;
        }
        if(j<k)j+=k;
    }
}
void fft(complex *x,int len,int sta)
{
    change(x,len);
    for(int m=2;m<=len;m<<=1)
    {
        complex Wn(cos(-sta*2*PI/m),sin(-sta*2*PI/m));
        for(int i=0;i<len;i+=m)
        {
            complex W(1,0);
            for(int j=i;j<i+m/2;j++)
            {
                complex x1=x[j],x2=W*x[j+m/2];
                x[j]=x1+x2,x[j+m/2]=x1-x2;
                W=W*Wn;
            }
        }
    }
    if(sta==-1)
        for(int i=0;i<len;i++)
            x[i].r/=len;
}
char s1[maxn],s2[maxn];
complex a[2*maxn],b[2*maxn];
int ans[2*maxn];
int main()
{
    while(~scanf("%s%s",s1,s2))
    {
        int len1=strlen(s1),len2=strlen(s2),len=1;
        while(len<len1*2||len<len2*2)len<<=1;
        for(int i=0;i<len1;i++)a[i]=complex(s1[len1-i-1]-'0',0);
        for(int i=len1;i<len;i++)a[i]=complex(0,0);
        for(int i=0;i<len2;i++)b[i]=complex(s2[len2-i-1]-'0',0);
        for(int i=len2;i<len;i++)b[i]=complex(0,0);
        fft(a,len,1);fft(b,len,1);
        for(int i=0;i<len;i++)a[i]=a[i]*b[i];
        fft(a,len,-1);
        for(int i=0;i<len;i++)ans[i]=(int)(a[i].r+0.5);
        for(int i=0;i<len;i++)
        {
            ans[i+1]+=ans[i]/10;
            ans[i]%=10;
        }
        len=len1+len2-1;
        while(ans[len]<=0&&len>0)len--;
        for(int i=len;i>=0;i--)printf("%c",ans[i]+'0');
        printf("\n");
    }
    return 0;
} 

你可能感兴趣的:(POJ 2389 Bull Math(FFT))