Efficient (cycles wise) algorithm to compute modulo 25?
I was inspired by Pax's answer and made a more general purpose algorithm.
int mod(int a, int b) {
int s = b;
while (s <= a) {
s <<= 1;
}
int r = a;
while (r >= b) {
s >>= 1;
if (s <= r) {
r -= s;
}
}
return r;
}
This subtracts power of two multiples of b
from a
until the result is found.
EDIT: added the if
condition to make it work properly.
As an example, if this is doing 100 % 7, it first works out that 7 * 2 * 2 * 2 * 2 = 112. Then it divides 112 (s
) by 2 and subtracts that from 100 (r
) (when s <= r
) and continually does this until the modulo is found. Therefore,
s = 112 / 2 = 56, r = 100 - 56 = 44
s = 56 / 2 = 28, r = 44 - 28 = 16
s = 28 / 2 = 14, r = 16 - 14 = 2
therefore, 100 % 7 = 2
I suggest reading Hacker's Delight. It describes very fast remainder algorithms for constant divisors. They would almost certainly beat a general algorithm.
Update: Here is some example code... It can probably be reworked to avoid the temporary long long.
unsigned mod25(unsigned n)
{
unsigned reciprocal = 1374389535; // 2^35 / 25
unsigned div25 = ((unsigned long long)n * reciprocal) >> 35;
return n - div25 * 25;
}