4

Why modulo operator is not working as intended in C and Java?

ProgramFOX
  • 6,131
  • 11
  • 45
  • 51
DDC
  • 834
  • 2
  • 9
  • 27

4 Answers4

5

Wikipedia has a nice table which shows the sign of the operation for various languages. In Python it is the sign of the divisor (26), in Java/C the sign of the dividend (-1).

assylias
  • 321,522
  • 82
  • 660
  • 783
3

Python's %-operator calculates the mathematical remainder, not the modulus. The remainder is by definition a number between 0 and the divisor, it doesn't depend on the sign of the dividend like the modulus.

Joni
  • 108,737
  • 14
  • 143
  • 193
  • Actually, you've got it backward. If y is positive, then "x mod y" will be between 0 and y-1, while the sign of "x remainder y" will depend upon that of x. I can't think of any occasions where I've ever used the "%" operator on a negative number and wanted the remainder, but for a long time the standard only mandated particular behavior for "%" with positive operands; in those cases "mod" and "remainder" were synonymous, and "mod" was easier to say, so that's the name that stuck. – supercat Sep 26 '14 at 19:05
1

It is working as specified.

The contract is that

a == (a/b) * b + (a % b)

and integer division truncates toward zero. So with a negative dividend, you get a negative remainder.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
0

Not sure about python but % operator in java returns the remainder obtained after the division.

-1%26

breaking it down:

            26)-1(0
                0
                ---
                -1 ---> Remainder as (-1+0=-1)
PermGenError
  • 45,977
  • 8
  • 87
  • 106