2

I am doing some calculations with % operator in java and python.

While doing calculations, i found out that % operator works differently in both languages when dealing with negative numbers.

For example

-21 % 4 = -1   // Java

-21 % 4 = 3    # Python

so i looked at some of the posts here on stackoverflow and found out that in java, % gives remainder whereas in python, % gives modulus. They both are same for positive numbers but give different result in case of negative numbers as shown in example above.

So i searched for the difference between modulus and remainder, read some posts online but difference between remainder and modulus is still not clear to me

Question

Can someone explain the difference between modulus and remainder in simple terms using above example?

  • 1
    You are getting 6 for the Python one? I am getting 3. – Matthew Gaiser Oct 01 '19 at 14:24
  • sorry, it was a typo. edited. –  Oct 01 '19 at 14:25
  • 1
    The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. – Bhawan Oct 01 '19 at 14:29
  • 1
    Modulus is always the same sign as the divisor and remainder the same sign as the quotient. – Bhawan Oct 01 '19 at 14:31
  • Check this answer: [mod and remainder](https://stackoverflow.com/a/13683709/6667539) – Paplusc Oct 01 '19 at 14:35

2 Answers2

-1

The implementation of the modulo operator is different in Python and languages like Java.

In Java, the result has the sign of the dividend, but in Python, the sign is from the divisor.

To achieve the Python’s result in Java, you can use:

(((n % m) + m) % m)

where n is the dividend and m – the divisor.

int a = (((-21% 4) + 4) % 4);
    System.out.println(a);                //a=3
Saif Ali
  • 7
  • 4
  • 2
    There is no modulus operator in Java. It is a remainder 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:47
-1

Unlike C or C++ or Java, Python's modulo operator (%) always return a number having the same sign as the denominator (divisor).

Example

(-5) % 4 = (-2 × 4 + 3) % 4 = 3.

(See for how the sign of result is determined for different languages.)

stacktome
  • 790
  • 2
  • 9
  • 32
  • There is no modulus operator in Java. It is a remainder 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:47