题目链接
力扣题解链接
少用乘法,到不用乘法
思路〇可以忽略, 就图一乐
class Solution { public: int multiply(int A, int B) { bool a[A][B]; return (int)sizeof(a); } };
class Solution { public: int multiply(int A, int B) { return (int)sizeof(bool[A][B]); } };
系数表示
通过\(FFT\)映射到点值表示
,乘法的次数为\(O(Nlog(N))\)的数量级点值表示
下做乘法,乘法的次数为\(O(N)\)的数量级系数表示
,乘法的次数为\(O(Nlog(N))\)的数量级可以不用乘法吗?可以!
a
×b
看成十进制下的a
×二进制下的b
b
按照二进制下的位
拆开来,于是就只要用加法代替乘法即可class Solution { public: int multiply(int A, int B) { int ans=0; for(long long a=max(A,B),b=min(A,B);b;b>>=1,a+=a)if(b&1)ans+=a; return ans; } };
class Solution { public: void mul(int&ans,long long a,long long b){ if(b==0)return; if(b&1)ans+=a; mul(ans,a+a,b>>1); } int multiply(int A, int B) { int ans=0; mul(ans,A,B); return ans; } };
const int N = 1e6+10; const double 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* 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; } } 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].r /= len; } Complex x1[N<<2]; Complex x2[N<<2]; int num[N<<1]; string mul(string s1,string s2) { int n=s1.size(); int m=s2.size(); int len=1; while(len < (n<<1) || len < (m<<1) ) len <<= 1; for(int i = 0; i < n; i++) x1[i] = Complex(s1[i]-'0',0); for(int i = n; i < len; i++)x1[i] = Complex(0,0); for(int i = 0; i < m; i++) x2[i] = Complex(s2[i]-'0',0); for(int i = m; i < len; i++)x2[i] = Complex(0,0); fft(x1,len,1); fft(x2,len,1); for(int i = 0; i < len; i++)x1[i] = x1[i]*x2[i]; fft(x1,len,-1); for(int i = 0; i <n+m; i++)num[i] = (x1[i].r+0.5); for(int i=n+m-2; i>0; i--)num[i-1]+=num[i]/10,num[i]%=10; string res=""; for(int i=0; i<n+m-1; i++)res+=to_string(num[i]); return res; } class Solution { public: int multiply(int A, int B) { return atoi(mul(to_string(A),to_string(B)).c_str()); } };
class Solution { public: int multiply(int A, int B) { int ans=0; long long a=max(A,B); long long b=min(A,B); while(b){ if(b&1)ans+=a; b>>=1; a+=a; } return ans; } };