I've been using modulo % and i noticed some discrepancy. Can anyone explain why this happens:
# ruby
-123 % 10
> 7
-7 % 10
> 3
Then in Java:
// Java
System.out.println(-123 % 10); // -3
System.out.println(-7 % 10); // -7
I've been using modulo % and i noticed some discrepancy. Can anyone explain why this happens:
# ruby
-123 % 10
> 7
-7 % 10
> 3
Then in Java:
// Java
System.out.println(-123 % 10); // -3
System.out.println(-7 % 10); // -7
It happens because in Java the result of the modulo has the same sign of the dividend. In Ruby it has the same signo of the divisor. From Ruby documentation:
x.modulo(y) means x-y*(x/y).floor
Alternatively you could use the remainder()
function that does the same thing.
The issue is that Java finds the remainder which is different than the modulo result. Ruby finds the least positive result out of an infinite number. So if you add the modulus (10) to the Java result, they will be the same.
A modulo operation says the for x congruent to m mod(n)
there exists an integer k
such that x - m = kn
Remainder - -123 % 10 = -3
Modulus - x = -123 % 10
so x + 123 = 10k
where k
is some integer. so x can be any one of ...,-23, -13, -3 ,7, 17, 27, ...