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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…