(模板)c++ 大数(正数加减乘除)

char ip[mxn];
struct bign {
    int len, dig[mxn];
    bign() {
        len = 0, dig[0] = 0;
    }
	bool input() {
        if(scanf("%s", ip) == EOF) return 0;
        if(strcmp(ip, "0") == 0) {
            len = 0, dig[0] = 0;
            return 1;
        }
        int n = strlen(ip);
        for( int i = 0; i < n; ++i )
            dig[i] = ip[n-i-1] - '0';
        len = n - 1;
        return 1;
    }
    void output() {
        for(int i = len; i >= 0; --i)
            printf("%d", dig[i]);
    }
    bign operator + (const bign &b) const {
        int i, carry;
        bign c;
        for(i = carry = 0; i <= len || i <= b.len || carry; ++i) {
            if(i <= len) carry += dig[i];
            if(i <= b.len) carry += b.dig[i];
            c.dig[i] = carry % 10;
			carry /= 10;
        }
        c.len = i - 1;
        return c;
    }
    bign operator + (const int &k) const {
        int i, b = k;
        bign c;
        for(i = 0; i <= len || b; ++i) {
            if(i <= len) b += dig[i];
            c.dig[i] = b % 10;
            b /= 10;
        }
        c.len = i - 1;
        return c;
    }
    bign operator * (const int &k) const {
        int i, carry, b = k;
        bign c;
        for(i = carry = 0;i <= len || carry; ++i) {
            if( i <= len ) carry += b * dig[i];
            c.dig[i] = carry % 10;
            carry /= 10;
        }
        i--;
        while(i && !c.dig[i]) --i;
        c.len = i;
        return c;
    }
    bign operator * (const bign &b) const {
        int i, j, carry;
        bign c;
        for(i = len + b.len + 1; i >= 0; -- i) c.dig[i] = 0;
        for(i = 0; i <= len; ++i) {
            carry = 0;
            for(j = 0; j <= b.len || carry; ++j) {
                carry += c.dig[i+j];
                if(j <= b.len) carry += dig[i] * b.dig[j];
                c.dig[i+j] = carry % 10;
                carry /= 10;
            }
        }
        i = len + b.len + 1;
        while(i && !c.dig[i]) --i;
        c.len = i;
        return c;
    }
};
//c为商, d为余数
void div(bign a, int b, bign &c, int &d) {
    int i;
    for(i = a.len, d = 0; i >= 0; --i) {
        d = d * 10 + a.dig[i];
        c.dig[i] = d / b;
        d = d % b;
    }
    i = a.len;
    while( i && !c.dig[i] ) -- i;
    c.len = i;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值