I apologize if this is a simple question but I\'m having trouble grasping the concept of modulus division when the first number is smaller than the second number. For exampl
I think you are confused between %(Remainder)
and /(Division)
operators.
When you say %
, you need to keep dividing the dividend until you get the remainder 0 or possible end. And what you get in the end is called Remainder
.
When you say /
, you divide the dividend until the divisor becomes 1. And the end product you get is called Quotient
I am going to add a more practical example to what "Jean-Bernard Pellerin" already said.
It is correct that if you divide 1 by 4 you get 0 but, Why when you do 1 % 4 you have 1 as result?
Basically it is because this:
n = a / b (integer), and
m = a % b = a - ( b * n )
So,
a b n = a/b b * n m = a%b
1 4 0 0 1
2 4 0 0 2
3 4 0 0 3
4 4 1 0 0
5 4 1 4 1
Conclusion: While a < b, the result of a % b will be "a"
First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics.
That said, you need to think in terms of integer-only division, as if there were no fractional values. Think of it as storing items that cannot be divided: you can store zero items of size 4 in a storage of overall capacity one. Your remaining capacity after storing the maximum number of items is one. Similarly, 13%5 is 3, as you can fit 2 complete items of size 5 in a storage of size 13, and the remaining capacity is 13 - 2*5 = 3
.
If you divide 1 by 4, you get 0 with a remainder of 1. That's all the modulus is, the remainder after division.
Another way to think of it as a representation of your number in multiples of another number. I.e, a = n*b + r
, where b>r>=0
. In this sense your case gives 1 = 0*4 + 1
. (edit: talking about positive numbers only)
Another nice method to clear things up, In modulus, if the first number is > the second number, subtract the second number from the first until the first number is less than the second.
17 % 5 = ?
17 - 5 = 12
12 % 5 = ?
12 - 5 = 7
7 % 5 = ?
7 - 5 = 2
2 % 5 = 2
Therefore 17 % 5, 12 % 5, 7 % 5 all give the answer of 2. This is because 2 / 5 = 0 (when working with integers) with 2 as a remainder.