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

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

    You could consider computing a greatest common factor for all your values, and then dividing them by that factor before doing your arithmetic operations, then multiplying again. This assumes that such a factor exists, however (for example, if A, B, C and D happen to be relatively prime, they won't have a common factor).

    Similarly, you could consider working on log-scales, but this is going to be a little scary, subject to numerical precision.

提交回复
热议问题