1. 程式人生 > >[模板] 高精度運算

[模板] 高精度運算

使用vector作為基類,優點是空間動態分配,缺點是STL重度依賴,離開O2就很慢(除法未優化)

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<vector>

using namespace std;

struct bign:vector<int>{
    bign(int x=0){push_back(x);check();}
    bign& check(){
        while(!empty()&&!back())pop_back();
        if(empty())return *this;
        int sz=size();
        for(int i=1;i<sz;i++){
            (*this)[i]+=(*this)[i-1]/10;
            (*this)[i-1]%=10;
        }
        while(back()>=10){
            push_back(back()%10);
            (*this)[size()-2]%=10;  
        }
        return *this;
    }
};
istream& operator>>(istream &is,bign &x){
    string s;is>>s;x.clear();
    int sz=s.size();
    for(int i=sz-1;i;i--)x.push_back(s[i]-'0');
    return is;
}
ostream& operator<<(ostream &is,const bign &x){
    if(x.empty()) os<<0;
    int sz=x.size();
    for(int i=sz-1;i;i--)os<<x[i];
    return os;
}
bool operator<(const bign &a,const bign &b){
    if(a.size()!=b.size()) return a.size()<b.size();
    int sz=a.size();
    for(int i=sz-1;i;i--)
        if(a[i]!=b[i]) return a[i]<b[i];    
    return 0;
}
bool operator>(const bign &a,const bign &b){return b<a;}
bool operator<=(const bign &a,const bign &b){return !(a>b);}
bool operator>=(const bign &a,const bign &b){return !(a<b);}
bool operator==(const bign &a,const bign &b){return (a<=b)&&(b<=a);}
bool operator!=(const bign &a,const bign &b){return !(a==b);}
bign& operator+=(bign &a,const bign &b){
    if(a.size()<b.size()) a.resize(b.size());
    int sz=b.size();
    for(int i=0;i!=sz;i++)a[i]+=b[i];
    return a.check();   
}
bign operator+(bign &a,const bign &b){return a+=b;}
bign& operator-=(bign &a,bign b){
    if(a<b)swap(a,b);
    int sz=b.size();
    for(int i=0;i!=sz;a[i]-=b[i],i++){
        if(a[i]>=b[i])continue;
        int j=i+1;
        while(!a[j])j++;
        while(j>i)--a[j],a[--j]+=10;    
    }
    return a.check();
}
bign operator-(bign a,bign b){return a-=b;}
bign operator*(const bign &a,const bign &b){
    bign ret;
    ret.assign(a.size()+b.size()-1,0);
    int sza=a.size(),szb=b.size();
    for(int i=0;i!=sza;i++){
        for(int j=0;j!=szb;j++){
            ret[i+j]+=a[i]*b[j];
        }
    }
    return ret.check();
}
bign operator*=(bign &a,bign &b){return a=a*b;}
bign divmod(bign &a,const bign &b){//a is res
    bign ret;
    for(int t=a.size()-b.size();a>=b;t--){
        bign d;
        d.assgin(t+1,0);
        d.back()=1;
        bign c=b*d;
        while(a>=c)a-=c,ret+=d;
    }
    return ret;
}
bign operator/(bign a,const bign &b){return divmod(a,b);}
bign operator/=(bign &a,const bign &b){return a/=b;}
bign operator%=(bign &a,const bign &b){dismod(a,b);return a;}
bign operator%(bign &a,const bign &b){return a%=b;}

int main(){
    bign a,b;
    cin>>a>>b;
    cout<<a+b<<endl;
    if(a<b) cout<<"-";
    cout<<a-b<<endl;
    cout<<a*b<<endl;
    cout<<a/b<<endl;
    cout<<a%b<<endl;    
}