The “most natural” definition of the div and mod functions
[incomplete: must add examples and more discussion]
Most programming languages include a “remainder” or “modulo” function, and also an integer division (“quotient”) function. Given two integers and
, let’s call the results of these functions
and
respectively.
For positive and
, it is clear what
and
should be:
is the largest integer
such that
, and
is the remainder which therefore satisfies
.
What should we do when, as frequently happens, is negative, or (as less frequently happens)
is negative?
For negative and positive
, there are two choices when
lies between two multiples of
(i.e.
):
(1) Set to the lesser value, so that
continues to hold, or
(2) Set to the greater (and therefore smaller in magnitude) value.
There are very good reasons why (1) is preferable to (2): it ensures that the function is always positive no matter what the value of
, so that, for example,
.
And indeed that is what the more recent programming languages do. There is a table on Wikipedia: C, C++, Java, Go(!), OCaml(!), PHP, all have the “bad” behaviour, while Maple, Mathematica, Microsoft Excel, Perl, Python, Ruby have the “good” behaviour. Some languages have separate functions for both behaviours (e.g. Haskell has quotRem
and divMod
functions, similarly Common Lisp, Fortran, MATLAB).
There’s also the question of what to do when is negative, which turns out not to matter much (as long as it’s consistent with the above). One defintion is to continue to have
be the lesser value, and the other is to continue to insist that
. Both are fine, though sometimes the latter is nicer.
These are elaborated in The Euclidean Definition of the Functions div and mod by Raymond T. Boute, ACM Transactions on Programming Languages and Systems, Vol 14, No. 2, April 1992.
[…] to this blog from my friend Shreevatsa which helped me look up the different ways of finding the remainder and […]
Modulo operator in C | Recursive Complexity
Mon, 2015-01-12 at 22:54:34