-10

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.

CubeJockey
  • 2,209
  • 8
  • 24
  • 31
bgreatfit
  • 55
  • 1
  • 10

4 Answers4

1

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.

ryekayo
  • 2,341
  • 3
  • 23
  • 51
1

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)
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
0

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.

Zarwan
  • 5,537
  • 4
  • 30
  • 48
0

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.

Daniel
  • 4,481
  • 14
  • 34