高精度大数运算模板

#define MAX 100000  
#define base 10000  
#define digit 4  
  
struct bigint  
{  
    int c[MAX];  
    int len;  
    void init()  
    {  
        len = 0;  
        memset(c,0,sizeof(c));  
    }  
  
    bigint()  
    {  
        init();  
        len = 1;  
    }  
  
    bigint(int n)  
    {  
        init();  
        do {  
            c[len++] = n%base;  
            n /= base;  
        } while(n);  
    }  
  
    bigint(char* s)  
    {  
        init();  
        for(int i=strlen(s);i>=0;i--)  
            c[i/4] = c[i/4]*10 + c[i] - '0';  
    }  
  
    bigint(const bigint & n)  
    {  
        *this = n;  
    }  
  
    bigint & operator = (const bigint & a)  
    {  
        len = a.len;  
        for(int i=0;i<len;i++) c[i] = a.c[i];  
        return *this;  
    }  
  
    bigint operator + (const bigint & a) const  
    {  
        bigint t;  
        t.len = max(a.len,len);  
        for(int i=0;i<t.len;i++)  
            t.c[i] = c[i]+a.c[i];  
        for(int i=0;i<t.len;i++)  
            t.c[i+1] += t.c[i]/base, t.c[i] %= base;  
        if(t.c[t.len]) t.len++;  
        return t;  
    }  
  
    bigint operator * (const bigint & a) const  
    {  
        bigint t;  
        t.len = a.len+len+2;  
        for(int i=0;i<len;i++) for(int j=0;j<a.len;j++)  
        {  
            t.c[i+j] += c[i]*a.c[j];  
            t.c[i+j+1] += t.c[i]/base;  
            t.c[i+j] %= base;  
        }  
        for(int i=0;i<t.len;i++)  
        {  
            t.c[i+1] += t.c[i]/base;  
            t.c[i] %= base;  
        }  
        while(!t.c[t.len-1]) t.len--;  
        return t;  
    }  
  
    void out()  
    {  
        printf("%d",c[len-1]);  
        for(int i=len-2;i>=0;i--)  
        {  
            printf("%04d",c[i]);  
        }  
    }  
  
    friend ostream & operator << (ostream & os,const bigint & a)  
    {  
        os << a.c[a.len - 1];  
        for(int i = a.len - 2;i>=0;i--)  
        {  
            os.width(digit);  
            os.fill('0');  
            os << a.c[i];  
        }  
        return os;  
    }  
  
    friend istream & operator >> (istream & is,bigint & a)  
    {  
        char s[MAX*4+1];  
        is>>s;  
        bigint t(s);  
        a = t;  
        return is;  
    }  
};  



你可能感兴趣的:(大数相加,相乘模板,高精度运算模板)