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

后端 未结 15 1172
萌比男神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:05

    E = max(A,B,C,D)
    A1 = A -E;
    B1 = B -E;
    C1 = C -E;
    D1 = D -E;
    

    then

    A*B - C*D = (A1+E)*(B1+E)-(C1+E)(D1+E) = (A1+B1-C1-D1)*E + A1*B1 -C1*D1
    

提交回复
热议问题