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

后端 未结 15 1009
萌比男神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 19:04

    This should work ( I think ):

    signed long long int a = 0x7ffffffffffffffd;
    signed long long int b = 0x7ffffffffffffffd;
    signed long long int c = 0x7ffffffffffffffc;
    signed long long int d = 0x7ffffffffffffffe;
    signed long long int bd = b / d;
    signed long long int bdmod = b % d;
    signed long long int ca = c / a;
    signed long long int camod = c % a;
    signed long long int x = (bd - ca) * a * d - (camod * d - bdmod * a);
    

    Here's my derivation:

    x = a * b - c * d
    x / (a * d) = (a * b - c * d) / (a * d)
    x / (a * d) = b / d - c / a
    
    now, the integer/mod stuff:
    x / (a * d) = (b / d + ( b % d ) / d) - (c / a + ( c % a ) / a )
    x / (a * d) = (b / d - c / a) - ( ( c % a ) / a - ( b % d ) / d)
    x = (b / d - c / a) * a * d - ( ( c % a ) * d - ( b % d ) * a)
    

提交回复
热议问题