How to avoid overflow in expr. A * B - C * D

后端 未结 15 1176
萌比男神i
萌比男神i 2021-01-29 18:18

I need to compute an expression which looks like: A*B - C*D, where their types are: signed long long int A, B, C, D; Each number can be really big (not

15条回答
  •  甜味超标
    2021-01-29 18:40

    If the result fits in a long long int then the expression A*B-C*D is okay as it performs the arithmetic mod 2^64, and will give the correct result. The problem is to know if the result fits in a long long int. To detect this, you can use the following trick using doubles:

    if( abs( (double)A*B - (double)C*D ) > MAX_LLONG ) 
        Overflow
    else 
        return A*B-C*D;
    

    The problem with this approach is that you are limited by the precision of the mantissa of the doubles (54bits?) so you need to limit the products A*B and C*D to 63+54 bits (or probably a little less).

提交回复
热议问题