BZOJ2179: FFT快速傅立叶 FFT实现高精度乘法
Code:
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#define setIO(s) freopen(s".in","r",stdin)
#define maxn 200000
#define pi 3.1415926535898
using namespace std;
int len=1,l,r[maxn<<1];
long long ans[maxn];
char str1[maxn],str2[maxn];
struct Cpx{
double x,y;
Cpx(double t1=0,double t2=0){x=t1,y=t2;}
}A[maxn<<1],B[maxn<<1],C[maxn<<1];
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 FFT(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 mid=1;mid<n;mid<<=1){
Cpx wn(cos(pi/mid),flag*sin(pi/mid)),x,y;
for(int j=0;j<n;j+=(mid<<1)){
Cpx w(1,0);
for(int k=0;k<mid;++k){
x=a[j+k],y=w*a[j+mid+k];
a[j+k]=x+y,a[j+mid+k]=x-y;
w=w*wn;
}
}
}
}
int main(){
//setIO("input");
int n;
scanf("%d",&n);
scanf("%s%s",str1,str2);
for(int i=0;i<n;++i) A[i].x=str1[n-i-1]-48;
for(int i=0;i<n;++i) B[i].x=str2[n-i-1]-48;
while(len<n+n) len<<=1,++l;
for(int i=0;i<len;++i)
r[i]=(r[i>>1]>>1)|((i&1)<<(l-1));
FFT(A,len,1),FFT(B,len,1);
for(int i=0;i<len;++i)
C[i]=A[i]*B[i];
FFT(C,len,-1);
for(int i=0;i<=len;++i) {
ans[i]+=(int)(C[i].x/len+0.5);
if(ans[i]>=10)
ans[i+1]+=ans[i]/10,ans[i]%=10,
len+=(len==i);
}
while(!ans[len]&&len>=0) --len;
while(len>=0) printf("%d",(int)ans[len]),--len;
return 0;
}