FFT A*B模板
从卿学姐那里偷了份FFT大数相乘的模板。。。果断交了一发HDU 1402
还不孬
1 //FFT 大整数乘法 2 #include<cstdio> 3 #include<cmath> 4 #include<cstring> 5 #include<algorithm> 6 7 using namespace std; 8 9 10 const int N = 500005; 11 const double pi = acos(-1.0); 12 13 char s1[N],s2[N]; 14 int len,res[N]; 15 16 struct Complex 17 { 18 double r,i; 19 Complex(double r=0,double i=0):r(r),i(i) {}; 20 Complex operator+(const Complex &rhs) 21 { 22 return Complex(r + rhs.r,i + rhs.i); 23 } 24 Complex operator-(const Complex &rhs) 25 { 26 return Complex(r - rhs.r,i - rhs.i); 27 } 28 Complex operator*(const Complex &rhs) 29 { 30 return Complex(r*rhs.r - i*rhs.i,i*rhs.r + r*rhs.i); 31 } 32 } va[N],vb[N]; 33 34 void rader(Complex F[],int len) //len = 2^M,reverse F[i] with F[j] j为i二进制反转 35 { 36 int j = len >> 1; 37 for(int i = 1;i < len - 1;++i) 38 { 39 if(i < j) swap(F[i],F[j]); // reverse 40 int k = len>>1; 41 while(j>=k) 42 { 43 j -= k; 44 k >>= 1; 45 } 46 if(j < k) j += k; 47 } 48 } 49 50 void FFT(Complex F[],int len,int t) 51 { 52 rader(F,len); 53 for(int h=2;h<=len;h<<=1) 54 { 55 Complex wn(cos(-t*2*pi/h),sin(-t*2*pi/h)); 56 for(int j=0;j<len;j+=h) 57 { 58 Complex E(1,0); //旋转因子 59 for(int k=j;k<j+h/2;++k) 60 { 61 Complex u = F[k]; 62 Complex v = E*F[k+h/2]; 63 F[k] = u+v; 64 F[k+h/2] = u-v; 65 E=E*wn; 66 } 67 } 68 } 69 if(t==-1) //IDFT 70 for(int i=0;i<len;++i) 71 F[i].r/=len; 72 } 73 74 void Conv(Complex a[],Complex b[],int len) //求卷积 75 { 76 FFT(a,len,1); 77 FFT(b,len,1); 78 for(int i=0;i<len;++i) a[i] = a[i]*b[i]; 79 FFT(a,len,-1); 80 } 81 82 void init(char *s1,char *s2) 83 { 84 int n1 = strlen(s1),n2 = strlen(s2); 85 len = 1; 86 while(len < 2*n1 || len < 2*n2) len <<= 1; 87 int i; 88 for(i=0;i<n1;++i) 89 { 90 va[i].r = s1[n1-i-1]-'0'; 91 va[i].i = 0; 92 } 93 while(i<len) 94 { 95 va[i].r = va[i].i = 0; 96 ++i; 97 } 98 for(i=0;i<n2;++i) 99 { 100 vb[i].r = s2[n2-i-1]-'0'; 101 vb[i].i = 0; 102 } 103 while(i<len) 104 { 105 vb[i].r = vb[i].i = 0; 106 ++i; 107 } 108 } 109 110 void gao() 111 { 112 Conv(va,vb,len); 113 memset(res,0,sizeof res); 114 for(int i=0;i<len;++i) 115 { 116 res[i]=va[i].r + 0.5; 117 } 118 for(int i=0;i<len;++i) 119 { 120 res[i+1]+=res[i]/10; 121 res[i]%=10; 122 } 123 int high = 0; 124 for(int i=len-1;i>=0;--i) 125 { 126 if(res[i]) 127 { 128 high = i; 129 break; 130 } 131 } 132 for(int i=high;i>=0;--i) putchar('0'+res[i]); 133 puts(""); 134 } 135 136 137 int main() 138 { 139 while(scanf("%s%s",s1,s2)==2) 140 { 141 init(s1,s2); 142 gao(); 143 } 144 return 0; 145 }