Integer division and modulus by constants.by Paul HsiehDivision is a very slow, complex procedure when implemented for general divisors. However, if the divisor is a constant we can simply use fixed point approximation methods to multiply by the reciprocal:
Clearly, (int)(((2^32)+b1)/b) is precalculated. Similarly, modulus for the number k*2^t (where k is odd) is calculated as:
For example, to calculate a (mod 320) the code would look like:
The approximation is very good for reasonably small "b" or "k*2^t". With some work, the constant multiplies can also be gotten rid of (which in many cases is a good idea since mul is not a very fast instruction for the x86 based PC.) See: constant multiplies for more information.



And if you just can't get enough of computational division algorithms, here are some papers about how they are done in modern CPUs today.
I wonder which method is being used in the graphics world these days ...