Compare A + B > C (64 bit) – Integer Overflow


Given three integers a, b and c (all of them are 64 bit signed integers, tex_6964aa0fd2f1c77a44f16097c9f53e38 Compare A + B > C (64 bit) - Integer Overflow beginner c / c++ code implementation math programming languages tricks to tex_f1cc5cca4576e3b99181f46e10e46a6a Compare A + B > C (64 bit) - Integer Overflow beginner c / c++ code implementation math programming languages tricks ), check if a + b > c.

Since a + b can overflow (or underflow) easily (when the sum is too big or too small to hold using a 64 bit signed integer), we should avoid this.

1
2
3
4
5
6
7
8
9
bool chk(long long a, long long b, long long c) {
    if(a >= 0 && b >= 0) {
        if(a > LLONG_MAX - b) return true;
    }
    if(a <= 0 && b <= 0) {
        if(a < LLONG_MIN - b) return false;     
    }     
    return a + b > c;
}
bool chk(long long a, long long b, long long c) {
    if(a >= 0 && b >= 0) {
        if(a > LLONG_MAX - b) return true;
    }
    if(a <= 0 && b <= 0) {
        if(a < LLONG_MIN - b) return false;     
    }     
    return a + b > c;
}

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
215 words
Last Post: Why Absolute Value of INT_MAX and INT_MIN is different?
Next Post: Coding Exercise - 1. Life, the Universe, and Everything - Learning LUA programming language

The Permanent URL is: Compare A + B > C (64 bit) – Integer Overflow

Leave a Reply