I don't really understand how modulus division works. I was calculating 5 % 6 and wound up with 5 and I don't understand why. I understand modulus without decimal values. E. G 16%3 = 5 r 1.
-
25 = 0x6 + 5 so the remainder is 5. – Tunaki Aug 31 '15 at 17:41
-
Thats your problem 5 % 6, shouldnt it be 6 % 5? – ryekayo Aug 31 '15 at 17:41
-
2This has nothing to do with java. – Kevin Aug 31 '15 at 17:47
-
2What don't you understand about it? Do you know what the modulus operator means? 6 goes into 5 exactly 0 times, with a remainder of 5. – David Aug 31 '15 at 17:48
-
1By the way: a question about mathematics is not on topic here and should be asked on the [Stack Exchange for maths](http://math.stackexchange.com/). – bcsb1001 Aug 31 '15 at 17:51
-
I'm voting to close this question as off-topic because this is not a programming question, and you can find an explanation of this very quickly and easily by searching the web. – Jesper Aug 31 '15 at 18:19
-
https://en.wikipedia.org/wiki/Modulo_operation – Reinstate Monica -- notmaynard Aug 31 '15 at 19:42
-
Modulus (MOD) Operator Repeated Sequences: https://www.bennadel.com/blog/2240-creating-repeated-sequences-with-the-modulus-mod-operator.htm – Tyler Rafferty Feb 10 '17 at 22:08
4 Answers
The problem with your calculation 5 % 6
is that it will ALWAYS give you remainder 5. If you tried 6 % 5
, that will give you 1 for an answer.

- 2,341
- 3
- 23
- 51
This isn't a programming question, as modulus is a mathematical operator not at all unique to Java or any programming language, but 5 mod 6 = 5 as it is the remainder after dividing by 6 (5 < 6 so the remainder is 5). 6 mod 5 = 1, as 6 > 5, so you subtract 5, then you are left with 1 and 1 < 6.
If it helps, here is a pseudocode illustration of modulus (for positive integers):
integer mod(integer a, integer b) {
if a < b:
return a
else:
return mod(a - b, b)
}

- 2,834
- 3
- 24
- 35
num1 % num2
The modulus operator divides num1 by num2 as integers (in other words, all results of division are rounded down to the nearest whole number) and outputs the remainder. In your case, 5/6 = 0 with a remainder of 5.
Another way of expressing the remainder is:
num1 = x*num2 + R
Where x is the result of the integer division num1/num2
and R is the remainder, which is the output of the modules operator. Again in your case, 5 = 0*6 + 5
.

- 5,537
- 4
- 30
- 48
Modulus operator is similar to the "remainder", but there are a technicalities that make it different when negative numbers are involved.
However, for your example, think of 5 % 6 as "the remainder of 5 divided by 6" Read left to right, just like division.

- 4,481
- 14
- 34