Faster modulus in C/C#?

后端 未结 7 1166
情话喂你
情话喂你 2020-12-25 13:07

Is there a trick for creating a faster integer modulus than the standard % operator for particular bases?

For my program, I\'d be looking for around 1000-4000 (e.g.

7条回答
  •  爱一瞬间的悲伤
    2020-12-25 13:24

    For powers of two 2^n, all you have to do is zero out all bits except the last n bits.

    For example (assuming 32 bit integers):

    x%2 is equivalent to x & 0x00000001

    x%4 is equivalent to x & 0x00000003

    In general x % (2^n) is equal to x & (2^n-1). Written out in C, this would be x & ((1<.

    This is because 2^n gives you a 1 in the n+1th bit (from the right). So 2^n-1 will give you n ones on the right, and zeros on the left.

提交回复
热议问题