I am new to Java, actually programming in general. I understand that the modulus operator (%) returns the remainder of two numbers, however, I do not understand why 17 % 40 = 1
Maybe this is a different and more helpful way to think about it.
When we apply division to integer numbers a
and b
, we are really trying to relate a
and b
like this:
a = Q * b + R
a
is some multiple of b
, plus some leftover. Q
and R
are integers; to keep this simple, let's also just think of non-negative numbers. The multiple, Q
, is the quotient and leftover, R
, is the remainder -- the smallest ones that make this relation work.
In most languages, a / b
gives you Q
, and and a % b
gives you R
. (In fact processors tend to compute both at once -- these are so related.)
So if a
is 17 and b
is 40, it only works if you write:
17 = 0 * 40 + 17
This is why a % b
must be 17.
(Note that it gets more complex when considering negative numbers.)