I am curious about these languages (Java, C …) which ignore mathematical definition of modulus operation.
What is the point of returning negative values in a module operation (that, by definition, should allways return a positive number)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I doubt that the remainder operator was deliberately designed to have those semantics, which I agree aren’t very useful. (Would you ever write a calendar program that shows the weekdays Sunday, Anti-Saturday, Anti-Friday, …, Anti-Monday for dates before the epoch?)
Rather, negative remainders are a side effect of the way integer division is defined.
If
A div Bis defined astrunc(A/B), you get C’s%operator. IfA div Bis defined asfloor(A/B), you get Python’s%operator. Other definitions are possible.So, the real question is:
Why do C++, Java, C#, etc. use truncating integer division?
Because that’s the way that C does it.
Why does C use truncating division?
Originally, C didn’t specify how
/should handle negative numbers. It left it up to the hardware.In practice, every significant C implementation used truncating division, so in 1999 these semantics were formally made a part of the C standard.
Why does hardware use truncating division?
Because it’s easier (=cheaper) to implement in terms of unsigned division. You just calculate
abs(A) div abs(B)and flip the sign if(A < 0) xor (B < 0).Floored division has the additional step of subtracting 1 from the quotient if the remainder is nonzero.