标签:2的幂位数大整数分治算法
#include <iostream> #include <cstring> #include <string> #include <cstdio> using namespace std; //500 digits at most struct Num{ int num[1000],len; Num(){ memset(num,0,sizeof(num)); len=1; } Num(const string &s){ len=s.size(); for(int i=0;i<len;++i){ num[i]=s[len-1-i]-'0'; } } Num& operator=(const Num& right){ copy(right.num,right.num+1000,this->num); len=right.len; return *this; } friend ostream& operator<<(ostream &os,const Num &output){ for(int i=output.len-1;i>=0;--i) os<<output.num[i]; return os; } friend Num operator+(Num &x,Num &y){ Num ans; ans.len=max(x.len,y.len); for(int i=0;i<ans.len;++i){ ans.num[i]=x.num[i]+y.num[i]; } for(int i=0;i<ans.len;++i){ ans.num[i+1]+=ans.num[i]/10; ans.num[i]%=10; } if(ans.num[ans.len]) ++ans.len; return ans; } friend Num operator-(const Num &left,const Num& right){ Num ans; ans.len=max(left.len,right.len); for(int i=0;i<ans.len;++i) ans.num[i]=left.num[i]-right.num[i]; for(int i=0;i<ans.len;++i){ if(ans.num[i]<0){ --ans.num[i+1]; ans.num[i]+=10; } } while(ans.len>=1 && !ans.num[ans.len-1]) --ans.len; return ans; } friend Num mul(const Num &x,const Num &y){ if(x.len==1 && y.len==1) return to_string(x.num[0]*y.num[0]); Num a,b,c,d,ans; int maxlen=max(x.len,y.len),len1=maxlen>>1; copy(x.num,x.num+len1,b.num); b.len=len1; copy(x.num+len1,x.num+maxlen,a.num); a.len=maxlen-len1; copy(y.num,y.num+len1,d.num); d.len=len1; copy(y.num+len1,y.num+maxlen,c.num); c.len=maxlen-len1; Num tem_ac=mul(a,c),tem_bd=mul(b,d),ac,bd,fin_cdab; Num cdab=mul(c+d,a+b)-tem_ac-tem_bd; copy(tem_ac.num,tem_ac.num+tem_ac.len,ac.num+len1*2); ac.len=tem_ac.len+2*len1; copy(cdab.num,cdab.num+cdab.len,fin_cdab.num+len1); fin_cdab.len=cdab.len+len1; ans=ac+fin_cdab; ans=ans+tem_bd; while(ans.len>1 && !ans.num[ans.len-1]) --ans.len; return ans; } friend Num operator*(const Num &x,const Num &y){ return mul(x,y); } }; int main() { string a,b; while(cin>>a>>b){ Num x=a,y=b; cout<<"***************************************************"<<endl; cout<<a<<endl<<"*"<<endl<<b<<endl<<"="<<endl<<x*y<<endl; cout<<"***************************************************"<<endl; } return 0; }
标签:2的幂位数大整数分治算法
原文地址:http://blog.csdn.net/fangpinlei/article/details/45030423