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

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

    Choose K = a big number (eg. K = A - sqrt(A))

    A*B - C*D = (A-K)*(B-K) - (C-K)*(D-K) + K*(A-C+B-D); // Avoid overflow.
    

    Why?

    (A-K)*(B-K) = A*B - K*(A+B) + K^2
    (C-K)*(D-K) = C*D - K*(C+D) + K^2
    
    =>
    (A-K)*(B-K) - (C-K)*(D-K) = A*B - K*(A+B) + K^2 - {C*D - K*(C+D) + K^2}
    (A-K)*(B-K) - (C-K)*(D-K) = A*B - C*D - K*(A+B) + K*(C+D) + K^2 - K^2
    (A-K)*(B-K) - (C-K)*(D-K) = A*B - C*D - K*(A+B-C-D)
    
    =>
    A*B - C*D = (A-K)*(B-K) - (C-K)*(D-K) + K*(A+B-C-D)
    
    =>
    A*B - C*D = (A-K)*(B-K) - (C-K)*(D-K) + K*(A-C+B-D)
    

    Note that Because A, B, C and D are big numbers, thus A-C and B-D are small numbers.

提交回复
热议问题