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

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

    You could try breaking the equation into smaller components which don't overflow.

    AB - CD
    = [ A(B - N) - C( D - M )] + [AN - CM]
    
    = ( AK - CJ ) + ( AN - CM)
    
        where K = B - N
              J = D - M
    

    If the components still overflow you could break them into smaller components recursively and then recombine.

提交回复
热议问题