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

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

    You could write each number in an array, each element being a digit and do the calculations as polynomials. Take the resulting polynomial, which is an array, and compute the result by multiplying each element of the array with 10 to the power of the position in the array (the first position being the largest and the last being zero).

    The number 123 can be expressed as:

    123 = 100 * 1 + 10 * 2 + 3
    

    for which you just create an array [1 2 3].

    You do this for all numbers A, B, C and D, and then you multiply them as polynomials. Once you have the resulting polynomial, you just reconstruct the number from it.

提交回复
热议问题