Today at work I had an interesting discussion with one of my coworkers. He was surprised when he had the following happen to him:
assert(-1 % 10 == -1) //Expecting 9
So when he came to ask me about it, I told him "well, that makes sense. When you divide -1 by 10, you get 0 with -1 remaining. His argument however was that the modulus operator is supposed to hold true to the "always positive" model. I did a little research and found that the modulus he was referring to looks like this:
Let q be the integer quotient of a and n. Let r be the remainder. Then:
a = n * q + r
The definition I was using, however, appears to be the Knuth version of modulus, which is:
Let q be the floor of a divided by n. Let r be the remainder. Then:
r = a - n * q
So, my question is why it ended up in the FORTRAN standard (and subsequently the C-standard) to have the modulus operator truncate toward 0? It seems like a misnomer to me to call it "modulus" and not "remainder" (In math, the answer really should be 9). Is this related to how hardware is doing the division?
For reference:
TLDR; Is hardware the reason the modulus operator truncates toward 0?
It seems like a misnomer to me to call it "modulus" and not "remainder" (In math, the answer really should be 9).
C calls it the % operator, and calls its result the remainder. C++ copies this from C. Neither language calls it the modulus operator. This also explains why the remainder is negative: because the / operator truncates towards 0, and (a / b) * b + (a % b)
should equal a
.
Edit: David RodrÃguez rightly points out that C++ does define a template class std::modulus
, which calls operator%
. In my opinion, that class is poorly named. Digging a little bit, it is inherited from STL where it was already named as it is now. The download for STL says "The STL was developed on SGI MIPSproTM C++ 7.0, 7.1, 7.2, and 7.2.1.", and as far as I can tell without actually having the compiler and hardware, MIPSpro passes the division to the CPU and MIPS hardware truncates to 0, which would mean std::modulus
has always been misnamed.