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
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"