Skip to content Skip to sidebar Skip to footer

Difference Between Modulus And Remainder

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 negati

Solution 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

Solution 2:

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.)

Post a Comment for "Difference Between Modulus And Remainder"