码迷,mamicode.com
首页 > 其他好文 > 详细

高精度

时间:2018-09-15 16:26:53      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:struct   bool   lse   ons   har   str   operator   while   ide   

const int _bit = 100;
struct py {
    int m[_bit+50], w;
    py() {memset(m, 0, sizeof(m)); w = 1;}
};
py bit_plus(py a, py b) {
    py ans;
    for(int i = 0; i < _bit; i++) {
        ans.m[i] += a.m[i] + b.m[i];
        ans.m[i+1] += ans.m[i] / 10;
        ans.m[i] %= 10;
    }
    return ans;
}
py bit_minus(py a, py b) {
    py ans;
    for(int i = 0; i < _bit; i++) {
        ans.m[i] += a.m[i] - b.m[i];
        ans.m[i+1] -= (-ans.m[i]) / 10;
        if(ans.m[i] < 0 && ans.m[i] % 10) ans.m[i+1]--;
        ans.m[i] = (ans.m[i]%10+10) % 10;
    }
    return ans;
}
bool bit_smaller(py a, py b) {
    for(int i = _bit-1; i >= 0; i--) {
        if(a.m[i] < b.m[i]) return 1;
        if(a.m[i] > b.m[i]) return 0;
    }
    return 0;
}
py operator + (py a, py b) {
    py ans;
    if(a.w == b.w) ans = bit_plus(a, b);
    else{
        if(bit_smaller(a, b)) {
            ans = bit_minus(b, a);
            ans.w = -1;
        }else ans = bit_minus(a, b);
    }
    if(a.w == -1) ans.w = -ans.w;
    return ans;
}
py operator - (py a) {
    a.w = -a.w;
    return a;
}
py operator - (py a, py b) {
    return a + (-b);
}
py bit_times(py a, py b) {
    py ans;
    for(int i = 0; i < _bit; i++) for(int j = 0; j < 30-i; j++) ans.m[i+j] += a.m[i] * b.m[j];
    for(int i = 0; i < _bit; i++) {
        ans.m[i+1] += ans.m[i] / 10;
        ans.m[i] %= 10;
    }
    return ans;
}
py operator * (py a, py b) {
    py ans = bit_times(a, b);
    ans.w = a.w * b.w;
    return ans;
}
int bit_count(py a) {
    for(int i = _bit-1; i >= 0; i--) if(a.m[i]) return i+1;
    return 0;
}
py operator << (py a, int b) {
    for(int i = _bit-1; i >= b; i--) a.m[i] = a.m[i-b];
    return a;
}
py bit_divide(py a, py b) {
    py ans, div;
    if(bit_smaller(a, b)) return ans;
    for(int i = _bit-1; i >= 0; i--) {
        div = (div << 1); div.m[0] = a.m[i];
        while(!bit_smaller(div, b)) {
            div = bit_minus(div, b);
            ans.m[i]++;
        }
    }
    for(int i = 0; i < _bit; i++) {
        ans.m[i+1] += ans.m[i] / 10;
        ans.m[i] %= 10;
    }
    return ans;
}
py operator / (py a, py b) {
    py ans = bit_divide(a, b);
    ans.w = a.w * b.w;
    return ans;
}
void print(py a) {
    if(bit_count(a) == 0) {
        putchar(‘0‘);
        return;
    }
    if(a.w == -1) putchar(‘-‘);
    int st = bit_count(a);
    for(int i = st-1; i >= 0; i--) putchar(‘0‘+a.m[i]);
}
py topy(long long a) {
    py ans; int ansn = 0;
    if(a < 0) {
        a = -a;
        ans.w = -1;
    }
    while(a) {
        ans.m[ansn++] = a % 10;
        a /= 10;
    }
    return ans;
}

高精度

标签:struct   bool   lse   ons   har   str   operator   while   ide   

原文地址:https://www.cnblogs.com/utopia999/p/9651038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!