Modular arithmetic and Euclid’s algorithm

Published

2023-08-05

Here’s a video (10:13) that gives a brief introduction to modular arithmetic. Modular arithmetic is useful in many applications, including

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,

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

Comprehension check

  1. What is 27 \pmod 8?
  2. What is 27 + 3 \pmod {11}?
  3. In C++, what is 14 % 5?
  4. In C++, what is 14 % -5?
  5. In C++, what is 7 % 0?

Answers: pǝuᴉɟǝpun / ɹnoɟ / ɹnoɟ / ʇɥƃᴉǝ / ǝǝɹɥʇ

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

All materials copyright © 2020–2023, The University of Vermont. All rights reserved.