51Nod 1028 - 大数乘法 V2(FFT)

【题目描述】
在这里插入图片描述
【思路】
FFT的基础应用,把一个大数从低位到高位看成一个多项式,大数想乘看成多项式想乘,多项式的自变量 x x 表示数字 10 10 ,乘完进位即可得到结果

#include<bits/stdc++.h>
using namespace std;
const double PI=acos(-1.0);
const int maxn=400005;

struct Complex {
	double x,y;
	Complex(double _x=0.0, double _y = 0.0) {
		x = _x;
		y = _y;
	}
	Complex operator - (const Complex &b) const {
		return Complex(x - b.x, y - b.y);
	}
	Complex operator + (const Complex &b) const {
		return Complex(x + b.x, y + b.y);
	}
	Complex operator * (const Complex &b) const {
		return Complex(x * b.x - y * b.y, x * b.y + y * b.x);
	}
};

void change(Complex y[], int len) {
	int i, j, k;
	for (i = 1, j = len / 2; i < len - 1; i++) {
		if (i < j) {
			swap(y[i], y[j]);
		}
		k = len / 2;
		while (j >= k) {
			j -= k;
			k /= 2;
		}
		if (j < k) {
			j += k;
		}
	}
	return ;
}

void fft(Complex y[], int len, int on) {
	change(y, len);
	for (int h = 2; h <= len; h <<= 1) {
		Complex wn(cos(-on * 2 * PI / h), sin(-on * 2 * PI / h));
		for (int j = 0; j < len; j += h) {
			Complex w(1, 0);
			for (int k = j; k < j + h / 2; k++) {
				Complex u = y[k];
				Complex t = w * y[k + h / 2];
				y[k] = u + t;
				y[k + h / 2] = u - t;
				w = w * wn;
			}
		}
	}
	if (on == -1) {
		for (int i = 0; i < len; i++) {
			y[i].x /= len;
		}
	}
}

Complex a[maxn],b[maxn];
char s1[maxn],s2[maxn];
int ans[maxn];

int main() {
	scanf("%s%s",s1,s2);
	int len1=strlen(s1);
	int len2=strlen(s2);
	int len=1;
	while(len<2*len1 || len<2*len2) len<<=1;
	for(int i=0;i<len1;++i) a[i]=Complex(s1[len1-1-i]-'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-1-i]-'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].x+0.5);
	for(int i=0;i<len-1;++i){
		ans[i+1]+=ans[i]/10;
		ans[i]%=10;
	}
	while(!ans[len-1]) --len;
	for(int i=len-1;i>=0;--i) printf("%d",ans[i]);
	puts("");
	return 0;
}