整理高精模板

const int width = 4;
const int mod = 1e4;

typedef long long LL;

struct HugeInt
{
    int a[50];
    int len;

    inline void clear()
    {
        memset(a, 0, sizeof(a));
        len = 0;
    }
};

HugeInt operator + (HugeInt a, HugeInt b)
{
    HugeInt c;
    c.clear();
    int maxlen = max(a.len, b.len);
    for(int i = 0; i < maxlen; ++i)
    {
        c.a[i] += a.a[i]+b.a[i];
        c.a[i+1] += c.a[i]/mod;
        c.a[i] %= mod;
    }
    c.len = maxlen;
    while(c.a[c.len])
        c.len++;
    return c;
}

HugeInt operator - (HugeInt a, HugeInt b)
{
    HugeInt c;
    c.clear();
    c.len = a.len;
    for(int i = 0; i < c.len; ++i)
    {
        c.a[i] += a.a[i]-b.a[i];
        if(c.a[i]<0)
        {
            a.a[i+1]--;
            c.a[i] += mod;
        }
    }
    while(!c.a[c.len-1] && c.len>=1)
        c.len--;
    return c;
}

HugeInt operator * (HugeInt a, HugeInt b)
{
    HugeInt c;
    c.clear();
    for(int i = 0; i < a.len; ++i)
        for(int j = 0; j < b.len; ++j)
            c.a[i+j] += a.a[i] * b.a[j];
    c.len = a.len + b.len - 1;
    for(int i = 0; i < c.len; ++i)
    {
        c.a[i+1] += c.a[i]/mod;
        c.a[i] %= mod;
    }
    while(c.a[c.len])
        c.len++;
    return c;
}

bool operator < (HugeInt a, HugeInt b)
{
    if(a.len != b.len)
        return a.len < b.len;
    else
    {
        for(int i = a.len-1; i >= 0; --i)
        {
            if(a.a[i] != b.a[i])
                return a.a[i] < b.a[i];
        }
    }
    return false;
}

HugeInt give(long long a)
{
    HugeInt re;
    re.clear();
    while(a)
    {
        re.a[re.len++] = a%mod;
        a /= mod;
    }
    return re;
}

HugeInt operator + (HugeInt a, LL b)
{
    return a + give(b);
}

HugeInt operator + (LL a, HugeInt b)
{
    return b + a;
}

HugeInt operator * (HugeInt a, LL b)
{
    return a * give(b);
}

HugeInt operator * (LL a, HugeInt b)
{
    return b * a;
}

HugeInt operator - (HugeInt a, LL b)
{
    return a - give(b);
}

HugeInt operator / (HugeInt a,LL b)
{
    HugeInt ans;
    ans.clear();
    ans=a;
    LL my=0;
    for(int i=ans.len-1; i>=0; i--)
    {
        ans.a[i]+=my;
        my=ans.a[i]%b*mod;
        ans.a[i]/=b;
    }
    while(!ans.a[ans.len-1])
        ans.len--;
    return ans;
}

void print(HugeInt a)
{
    printf("%d", a.a[a.len-1]);
    for(int i = a.len-2; i>=0; --i)
        printf("%04d", a.a[i]);
}

猜你喜欢

转载自www.cnblogs.com/pfypfy/p/9052314.html