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 , 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 is contained in :
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:
.
Note that this is only valid for a non-negative divisor , however the generalization is rather trivial and as is common practice to say, left as an exercise for the reader :).