Modular arithmetic and Euclid’s algorithm
Here’s a video (10:13) that gives a brief introduction to modular arithmetic. Modular arithmetic is useful in many applications, including
- testing odd or even
- calculating a greatest common divisor of two integers (e.g., Euclidean algorithm)
- algorithms for testing primality,
- hashing, and
- implementing many cyclic behaviors.
Note that % in C++ isn’t strictly the modulus operator it is the “remainder after division” operator. So you may get answers that are a little surprising when working with integers. For example, in C++ there’s a difference between 3 / 2 (where both operands are integers) and 3.0 / 2.0 (where operands are floats). (If you’ve seen the // integer division operator in Python, this might ring a bell.) So,
3 / 2 == 1(the integer part of the division, tossing any fractional portion)3.0 / 2.0 == 1.5(as you’d expect)
Sometimes things behave as expected, for example, in C++, 17 % 7 == 3, but 17 % -5 == 2, and -4 % 1 == 0. Wait! What?
Don’t panic. Here’s a formula that will always give you the correct answer in C++: (a / b) * b + (a % b) == a.
Remember: a / b here is integer division, so (a / b) * b isn’t always a. Here are examples for finding the remainder of integer division for the examples given above. First, let’s rearrange terms so that we have (a % b) on the right hand side: a - (a / b) * b == a % b.
So, 17 - (17 / -5) * -5 == 17 % -5. Now, 17 / -5 == -3, and `-3 * -5 == 15, so we have 17 - 15 == 2, and thus 17 % -5 == 2.
Next, let’s do -4 % 1.
-4 - (-4 / 1) * 1 == -4 % 1. Now, 4 / -1 == -4, and -4 * 1 == -4, therefore we have -4 - (-4) == 0, and thus -4 % 1 == 0.
See: Essential Algorithms, pp. 33–34 for more on Euclid’s algorithm.
Further reading
- https://en.wikipedia.org/wiki/Modular_arithmetic (Wikipedia)
Comprehension check
- What is 27 \pmod 8?
- What is 27 + 3 \pmod {11}?
- In C++, what is
14 % 5? - In C++, what is
14 % -5? - In C++, what is
7 % 0?
Answers: pǝuᴉɟǝpun / ɹnoɟ / ɹnoɟ / ʇɥƃᴉǝ / ǝǝɹɥʇ
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.