What does precisely the modulo operator do?

An integer n is said to divide another integer a when there is an integer q such that
a = q*n. In other words, nothing remains after the division. For example 2 divides 4. We call n the divisor, a the dividend, and q the quotient. However, 3 does not divide 7 because there is no integer q such that 7 = q*3. The integer 7 contains no more than two 3s and there will be a leftover of 1. This is called the remainder and is denoted by r. From this, we have the following equation:

a = q*n + r where 0 <= |r| < |n|

Most programming languages provide an operator that computes r from a and n. For example, C/C++ provide the % operator. It is sometimes called the modulo operator and sometimes the remainder operator. Unfortunately, different languages implement this operator in different ways. In fact, it also depends on the underlying hardware. So it’s critical to fully understand what kind of modulo operator your programming language is providing. Continue reading