抄写借鉴了许多题解之后,由于害怕板子找不到了我决定写一篇博客来总结一下高精的加减乘除.当然了其实只有加和乘除罢了.顺便一说,我还不会压位QWQ

高精度加法(高精+高精)

其实就是暴力模拟列竖式,非常易懂

inline node super_plus(node a, node b) {
    node ans;
    memset(ans.c, 0, sizeof(ans.c));
    int la = a.length, lb = b.length, lc = max(la, lb);
    for (int i = 1; i <= lc; ++i) {
        ans.c[i] += a.c[i] + b.c[i];
        ans.c[i + 1] += (ans.c[i] >= 10);//处理进位
        ans.c[i] -= 10 * (ans.c[i] >= 10);
    }
    if (ans.c[lc + 1]) lc++;//每个高精度数用结构体保存
    ans.length = lc;//结构体中记录长度和数值.
    return ans;
}

高精度乘法(高精乘单精)

inline node super_mul(node x, int y) {
    int lx = x.length, lr;
    node ret; lr = lx + 10;//保险起见
    for (int i = 1; i <= lx; ++i)
        ret.c[i] += x.c[i] * y;//由于我不会压位,所以不担心爆炸
    for (int i = 1; i <= lr; ++i) {
        ret.c[i + 1] += ret.c[i] / 10;
        ret.c[i] %= 10;//乘完了再进位
    }
    while (ret.c[lr + 1]) lr++;//记录长度
    while (!ret.c[lr]) lr--;//去除前导零(前面的都是为了保证确实是前导的0
    ret.length = lr;//保存长度
    return ret;
}

高精度乘法(高精乘高精)

inline node super_mul(node x, node y) {
    int lx = x.length, ly = y.length, lr = lx + ly - 1;
    //乘积最小位数是乘数位数相加-1
    node ret;
    memset(ret.c, 0, sizeof(ret.c));
    for (int i = 1; i <= lx; ++i)
        for (int j = 1; j <= ly; ++j)
            ret.c[i + j - 1] += x.c[i] * y.c[j];
    for (int i = 1; i <= lr; ++i) {
        ret.c[i + 1] += ret.c[i] / 10; 
        ret.c[i] %= 10;//同样由于不压位可以先乘后进
    }
    if (ret.c[lr + 1]) lr++;//最多增加一位
    ret.length = lr;
    return ret;
}

高精度除法(高精除单精)

高精除高精考了我就认栽

inline node super_divid(node x, int y) {
    node ret;
    int lr = x.length;
    for (int i = lr; i; --i) {//暴力模拟
        ret.c[i] = x.c[i] / y;
        x.c[i] %= y;
        x.c[i - 1] += x.c[i] * 10;
    }
    while (ret.c[lr] == 0 && lr > 1) lr--;
    ret.length = lr;
    return ret;
}

附赠:高精max/高精快速幂/高精重载大于号

inline node max(node x, node y) {//哈哈
    return x > y ? x : y;//重载运算符在下面
}

bool operator > (const node &y) const {
    if (length == y.length) {
        int i;
        for (i = length; i > 1 && c[i] == y.c[i]; --i);
        if (i >= 1) return c[i] > y.c[i];
        else return false;
    }
    else return length > y.length;
}

inline node super_pow(int times) {//哈哈,其实没啥区别的
    node ans, temp = base;
    memset(ans.c, 0, sizeof(ans.c));
    ans.c[1] = 1, ans.length = 1;
    while (times) {
        if (times & 1)
            ans = super_mul(ans, temp);
        temp = super_mul(temp, temp);
        times >>= 1;
    }
    return ans;
}

——Gensokyo