Help with Modulo of 1

Why is the modulo of 1 (almost) always 1?

1 % -999999999999999 === 1
// expected output: true
1 % -10 === 1
// expected output: true
1 % -2 === 1
// expected output: true
1 % -1 === 1
// expected output: false
1 % 1 === 1
// expected output: false
1 % 2 === 1
// expected output: true
1 % 10 === 1
// expected output: true
1 % 999999999999999 === 1 
// expected output: true

So long as the dividing number is > 1 or < -1, the answer is 1.

However, if you were to calculate 1 / 10 = 0.1. My guess is that the fixed modulo results has to do with types, but I am hoping to get a better understanding.

Reference: freeCodeCamp Challenge Guide: Chunky Monkey

I just noticed something silly! If you use the modulo operator on a divisor (dividing number) that doesn’t evenly divide the dividend (number being divided) it returns the dividend.

1 % 9999
// expected output: 1
2 % 9999
// expected output: 2
999 % 1000
// expected output: 999

A % B

A % B is always the remainder you get when you do A / B using long division.

The way that this works is, it tries to divide A by B – it’s the equivalent of saying, what’s 2 / 1000 using long division? that would be 0 with a remainder of 2. The same would go for any number A that’s smaller than any number B. In other works, when A < B, A / B is always 0 with a remainder A. Therefore, when A < B, A % B is always A.

When A > B:
Let’s take 100 % 2 – or 100 / 2. 100 / 2 is 50 with a remainder 0. So 100 % 2 is 0. So we can say that A > B when B evenly divides A, is 0. Similarly, 9 % 3 is 0, 80 % 4 is 0, etc.

But let’s say we do 99 % 2? 99 / 2 is 48 with a remainder 1. So 99 % 2 is 1. Similarly, for 104 = A and 5 =B, 104 / 5 is 20 with a remainder of 4. So 104 % 5 is 4. Also remember that a remainder can’t be larger than the thing it’s being divided by. So in these cases, the remainder is at most B - 1.

So if we sum up some general rules:
for A % B:

  1. If A < B, then A % B is always A.
  2. If A > B, and A / B is a whole number (ie. B evenly divides A), then A % B is 0.
  3. If A > B, and A / B is not a whole number, then A % B is at most B - 1.

Here’s some additional resources that might help if the above was confusing:


https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/what-is-modular-arithmetic

2 Likes

@lekha that was an awesome answer. Thank you very much for breaking this down for me. I found it clarified my thoughts on the modulus (modulo) operator quite a bit.