Implementing mod function in C

by alex

Something some people don’t realize is that C and several other programming languages don’t offer you the standard modulo operation but simply a remainder operation (this issue has been in any case discussed countless times, e.g. see, although most of the times without offering a solution).

The problem arises when people try to use the remainder operator, % or \text{rem} , for the modulo without realizing the implications of doing so.
I recall when a programmer I knew tried to write C code for a steering angle sensor system using the % operator for the mod operation (which was needed by the algorithm), leading to erratic and difficult to debug results (in this case, a function that was supposed to be smooth exhibited erratic jumps), leaving me the job to understand the algorithm and then find the bug.
Note that the C standard defines the remainder of an integer division via the % operator for positive integers. For negative integers the operation is implementation dependent and only fixed by the C99 standard or newer. Note that the remainder can be negative but the modulo can’t, and that \mod(a,b) is contained in [0,b[ :

Modulo vs remainder operation for fixed divisor.

The question is then, if the remainder operation, % here also denoted as rem is available, how to leverage this to calculate the modulo operation? And here’s one way of doing it:

\mod (a,b) = \begin{cases} 0, & a = 0 \vee b = 0\\ b - \text{rem}(-a -1, b) -1, &a<0 \\ \text{rem} (a,b), &a>0\end{cases}.
Note that this is only valid for a non-negative divisor b, however the generalization is rather trivial and as is common practice to say, left as an exercise for the reader :).