0

Say, let the dividend be -4 and the divisor be 3.

By the division theorem (or the division algorithm), we have -4 = -2 * 3 + 2 and thus the remainder is 2.

On the other hand, if we do int r = (-4) % 3; in java, we get r = -1. I interpret this result as first find the remainder obtained from the division of the absolute values of the dividend and the divisor, then attach the sign of the dividend to it.

May I ask if my interpretation is correct? How exactly and why does the computer find the remainder in such a way? How to understand the difference between these two types of remainders?

J-A-S
  • 368
  • 1
  • 8
  • 1
    % is for modulo arithmetic. ```-1``` is equivalent to ```2``` in modulo ```3```. – ewokx May 21 '21 at 03:14
  • Does this answer your question? [Difference between modulus and remainder](https://stackoverflow.com/questions/58186867/difference-between-modulus-and-remainder) – kaya3 May 21 '21 at 03:32
  • 2
    @ewong No it isn't. % is a remainder operator, not a modulo operator. [JLS #15.17.3](https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.17.3). – user207421 May 21 '21 at 03:43
  • By the 'division theorem', -4/3 is *-1*, not -2, so the remainder is therefore -1. Your arithmetic is incorrect. – user207421 May 21 '21 at 03:45
  • @kaya No it doesn't. – user207421 May 21 '21 at 03:47
  • 2
    @user207421 Hi, I think by 'division theorem' I mean the division theorem in [elementary number theory](https://en.wikipedia.org/wiki/Euclidean_division#Division_theorem) – J-A-S May 21 '21 at 03:48
  • Whatever you may think you mean, your calculation of the quotient as -2 remains incorrect, and so therefore is your calculation of the remainder. – user207421 May 21 '21 at 03:54

1 Answers1

3

You can write -4 = -2 * 3 + 2, or you can write -4 = -1 * 3 - 1. Both are meaningful in different ways, and both are used by different languages. The option Java chooses is for the sign of the remainder to match the sign of the left hand operand to division and modulo (the dividend). Since -4 is negative, the remainder -1 is chosen.

You can read more about the details in JLS section 15.17.3:

... the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264