The % remainder operator in Java
Aug 28, 2017 · 1 min read
what is the result of 3 % 4?
what is the result of -3 % 4?
what is the result of -3 % -4?
The answer is it’s language dependent!
I will tell you about the magic formula that Java uses to calculate the reminder of two quantities (yes, I call them quantities since you can use it for both integer and floating point numbers).
Here you go the formula:
a = (a/b)*b + a%b
so a%b = a- (a/b)*b
note: the “/” is the integer division
take some time to try a few examples yourself with this formula :)
-3 % 4 = -0*(4) + -3 => -3%4 = -3
3 % -4 = -0*(-4) + 3 => 3%4 = 3
3.2 % -4 = -0*(-4) + 3.2 => 3%4 = 3.2
