4

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

ProgramFOX
  • 5,801
  • 11
  • 44
  • 50
DDC
  • 752
  • 1
  • 7
  • 24

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
  • 310,138
  • 72
  • 642
  • 762
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
  • 105,306
  • 12
  • 136
  • 187
  • 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
  • 178,696
  • 16
  • 303
  • 427
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,111
  • 8
  • 85
  • 106