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

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

    Note that this is not standard since it relies on wrap-around signed-overflow. (GCC has compiler flags which enable this.)

    But if you just do all the calculations in long long, the result of applying the formula directly:
    (A * B - C * D) will be accurate as long as the correct result fits into a long long.


    Here's a work-around that only relies on implementation-defined behavior of casting unsigned integer to signed integer. But this can be expected to work on almost every system today.

    (long long)((unsigned long long)A * B - (unsigned long long)C * D)
    

    This casts the inputs to unsigned long long where the overflow behavior is guaranteed to be wrap-around by the standard. Casting back to a signed integer at the end is the implementation-defined part, but will work on nearly all environments today.


    If you need more pedantic solution, I think you have to use "long arithmetic"

提交回复
热议问题