整形大数加法、乘法、次方【模版】

 

#define CLR(a,v) memset(a,v,sizeof(a))
const int base = 1000;
struct BigNum
{
    int d[55],len;
    BigNum(int l=0){CLR(d,0);len=l;}
    BigNum(char* num,int l=0)
    {
        if(!l)
            l = strlen(num);
        len = -1;
        for(int i=1;i<=l/3;i++)
            if(sscanf(num+l-3*i,"%3d",&d[++len])==0)
                break;
        if(l%3 == 1)
            sscanf(num,"%1d",&d[++len]);
        else if(l%3 == 2)
            sscanf(num,"%2d",&d[++len]);
    }
    BigNum operator * (const BigNum& B)
    {
        BigNum C(len+B.len);
        for(int i=0;i<=len;i++)
            for(int j=0;j<=B.len;j++)
                C.d[i+j] += d[i]*B.d[j];
        C.upbit();
        return C;
    }
    BigNum operator + (const BigNum& B)
    {
        int l = max(len,B.len);
        BigNum C(l);
        for(int i=0;i<=len;i++)
            C.d[i] += d[i];
        for(int i=0;i<=B.len;i++)
            C.d[i] += B.d[i];
        C.upbit();
        return C;
    }
    bool operator < (const BigNum& B)
    {
        if(len < B.len)
            return true;
        if(len > B.len)
            return false;
        for(int i=len;i>=0;i--)
            if(d[i] < B.d[i])
                return true;
            else if(d[i] > B.d[i])
                return false;
        return false;
    }
    bool operator == (const BigNum& B)
    {
        if(len != B.len)
            return false;
        for(int i=0;i<=len;i++)
            if(d[i] != B.d[i])
                return false;
        return true;
    }
    bool operator <= (const BigNum& B)
    {
        return (*this)<B || (*this)==B;
    }
    BigNum Pow(int n)
    {
        BigNum B(*this),Ans("1");
        while(n)
        {
            if(n&1)
                Ans = Ans*B;
            B = B*B;
            n >>= 1;
        }
        return Ans;
    }
    void upbit()
    {
        for(int i=0;i<=len;i++)
            if(d[i] >= base)
            {
                d[i+1] += d[i]/base;
                d[i] %= base;
            }
        if(d[len+1])
            len++;
    }
    void print()
    {
        printf("%d",d[len]);
        for(int i=len-1;i>=0;i--)
            printf("%03d",d[i]);
        puts("");
    }
};

 

 

 

 

 

 

你可能感兴趣的:(模版)