Avoiding overflow in integer multiplication followed by division

后端 未结 4 1693
失恋的感觉
失恋的感觉 2020-12-31 08:32

I have two integral variables a and b and a constant s resp. d. I need to calculate the value of (a*b)>>s

4条回答
  •  执笔经年
    2020-12-31 09:05

    I haven't exhaustively tested this, but could you do the division first, then account for the remainder, at the expense of extra operations? Since d is a power of two, all the divisions can be reduced to bitwise operations.

    For example, always assume a > b (you want to divide the larger number first). Then a * b / d = ((a / d) * b) + (((a % d) * b) / d)

提交回复
热议问题