How do computers find modulus?

前端 未结 6 1744
时光说笑
时光说笑 2021-01-04 14:15

Is there some cool algorithm with bit wise operations?

6条回答
  •  暖寄归人
    2021-01-04 14:55

    Also checking the modulo 2 is easy, as it only need to check the least significant bit, usually.

    Quoting wikipedia:

    For special cases, on some hardware, faster alternatives exist. For example, the modulo of powers of 2 can alternatively be expressed as a bitwise AND operation:

    x % 2n == x & (2n - 1)

    Examples (assuming x is a positive integer):

    x % 2 == x & 1

    x % 4 == x & 3

    x % 8 == x & 7

    In devices and software that implement bitwise operations more efficiently than modulo, these alternative forms can result in faster calculations.

提交回复
热议问题