I am writing a library for MIPS which I can’t use floating point calculations I.E. modulos, division, multiplication.
I’ve written division and multiplication functions in C and then I translated that code to MIPS.
However I am lost on how to go about writing a function to calculate modulo via C using only addition or subtraction.
How can I write a function to calculate modulo using ONLY addition and subtraction?
Note: The following code snippets only work when both operands are positive. I have omitted any handling of negative values because the results of
x % ywhen one or both operands are negative vary between different languages and platforms. In general you can just calculateabs(x) % abs(y)and then perform some transformation on the result.The simplest way to calculate
x % yusing only only addition and subtraction is to just repeatedly subtractyuntil the remaining value is less thany:However, this approach is fairly inefficient. A more complex but faster method is to use binary long division. This is similar to regular long division except in binary the result at each step is either
0or1instead of0..9. A basic approach to calculatingx % ywith BLD looks like this:One gotcha in the above: the
divisor <= INT_MAX/2is necessary to stop overflow indivisor <<= 1whenx > MAX_INT/2.Additionally
divmod, which gives you both the quotient and the modulus in one calculation, looks almost exactly the same:Finally, note that if
yis a power of 2, you can cheat. In this casex % yis justx & (y - 1).