Faster modulus in C/C#?

If the denominator is known at compile time to be a power of 2, like your example of 2048, you could subtract 1 and do a bitwise-and.

That is:

n % m == n & (m - 1) 

…where m is a power of 2.

For example:

22 % 8 == 6

         Dec       Bin
       -----     -----
22 & (8 - 1) =   10110 
               & 00111 
               -------
           6 =   00110

Bear in mind that a good compiler will have its own optimizations for %, maybe even enough to be as fast as the above technique. Arithmetic operators tend to be pretty heavily optimized.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)