[模板]高精度四则运算
struct Number{
int a[N],n;bool POrN;
void init(){
memset(a,0,sizeof(a));
n=1;POrN=true;
}
void read(){
init();--n;
char c=getchar();
while(!isdigit(c)){
if(c=='-') POrN=false;
c=getchar();
}
while(isdigit(c)){
a[n++]=c-'0';c=getchar();
}
}
void write(){
if(!POrN) cout<<"-";
for(int i=0;i<n;++i) cout<<a[i];
}
Number abs(const Number a){
Number c=a;
c.POrN=true;return c;
}
friend bool operator < (const Number a,const Number b){
if(a.POrN^b.POrN) return !a.POrN;
if(a.n^b.n) return a.n<b.n;
for(int i=0;i<a.n;++i)
if(a.a[i]^b.a[i]) return a.a[i]<b.a[i];
return false;
}
friend bool operator <= (const Number a,const Number b){
if(a.POrN^b.POrN) return !a.POrN;
if(a.n^b.n) return a.n<b.n;
for(int i=0;i<a.n;++i)
if(a.a[i]^b.a[i]) return a.a[i]<=b.a[i];
return false;
}
friend bool operator > (const Number a,const Number b){
return b<a;
}
friend bool operator >= (const Number a,const Number b){
return b<=a;
}
void tran(){
for(int i=0;i<(n>>1);++i){
swap(a[i],a[n-i-1]);
}
}
Number add(Number a,Number b){
Number c;c.init();
c.n=max(a.n,b.n);
a.tran();b.tran();
for(int i=0;i<c.n;++i){
c.a[i]+=a.a[i]+b.a[i];
if(c.a[i]>=10){
c.a[i]-=10;++c.a[i+1];
}
}
while(c.a[c.n]) ++c.n;
c.tran();
return c;
}
Number sub(Number a,Number b){
Number c;c.init();
c.n=max(a.n,b.n);
a.tran();b.tran();
for(int i=0;i<c.n;++i){
c.a[i]+=a.a[i]-b.a[i];
if(c.a[i]<0) c.a[i]+=10,--c.a[i+1];
}
while(c.n>1&&!c.a[c.n-1]) --c.n;
c.tran();
return c;
}
friend Number operator + (Number a,Number b){
Number c;bool fl=false;
if(a.POrN^b.POrN){
if(!a.POrN){
swap(a,b);fl=true;
}
if(a.abs(a)<b.abs(b)){
c=c.sub(b,a);c.POrN=false;
}
else{
c=c.sub(a,b);c.POrN=true;
}
}
else{
c=c.add(a,b);c.POrN=a.POrN;
}
if(fl) swap(a,b);
return c;
}
friend Number operator - (const Number a,const Number b){
Number c=b;c.POrN=!c.POrN;return a+c;
}
friend Number operator * (Number a,Number b){
Number c;c.init();
c.n=a.n+b.n;
c.POrN=!(a.POrN^b.POrN);
a.tran();b.tran();
for(int i=0;i<a.n;++i)
for(int j=0;j<b.n;++j)
c.a[i+j]+=a.a[i]*b.a[j];
for(int i=0;i<c.n;++i)
if(c.a[i]>10){
c.a[i+1]+=c.a[i]/10;c.a[i]%=10;
}
while(c.n>1&&!c.a[c.n-1]) --c.n;
a.tran();b.tran();c.tran();
return c;
}
bool cmp(Number c,int s,int t){
if(t-s>n) return true;
if(t-s<n) return false;
for(int i=0;i<n;++i){
if(a[i]==c.a[s+i]) continue;
return c.a[s+i]>a[i];
}
return true;
}
void sub(Number b,int s,int t){
for(int i=t-1,j=b.n-1;j>=0;--i,--j){
a[i]-=b.a[j];
if(a[i]<0) a[i]+=10,--a[i-1];
}
return;
}
friend Number operator / (Number a,Number b){
Number c,d=a;c.init();
c.POrN=!(a.POrN^b.POrN);c.n=0;
for(int s=0,t=b.n;t<=d.n;){
while(b.cmp(d,s,t)){
d.sub(b,s,t);++c.a[c.n];
if(!d.a[s]) ++s;
}
++c.n;++t;
if(!d.a[s]) ++s;
}
int cnt=0;
while(cnt<c.n&&!c.a[cnt]) ++cnt;
c.n-=cnt;
for(int i=0;i<c.n;++i)
c.a[i]=c.a[i+cnt];
if(!c.n){
++c.n;c.POrN=true;
}
return c;
}
};
2020-01-01 10:53:51