Modulus operator

The modulus operator returns the remainder of an integer division. Sometimes written \(n \bmod m\) in mathematical expressions, the syntax in C++ is n % m. From the definition of remainder, \(n \bmod m\) is the integer \(r\) such that \(n = qm + r\) for \(q\) an integer, and \(|r| < |m|\).

Therefore, the result of \(n \bmod m\) must be between 0 and \(m-1\) when \(n\) and \(m\) are positive integers. For example, \(5 \bmod 3 = 2\); \(25 \bmod 3 = 1\), \(5 \bmod 7 = 5\), and \(5 \bmod 5 = 0\).

A common source of error is mixing up modulus and integer division operations.

int quotient = 7 / 3;

int remainder = 7 % 3;

The first operator, integer division, yields 2. The second operator yields 1. Thus, 7 divided by 3 is 2 with 1 left over.

This program shows the difference between the division operator and the modulus operator.

The modulus operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another: if x % y is zero, then x is divisible by y.

Also, you can use the modulus operator to extract the rightmost digit or digits from a number. For example, x % 10 yields the rightmost digit of x (in base 10). Similarly x % 100 yields the last two digits.

Construct a block of code that prints the remainder of 18 when divided by 13.

Construct a function that prints whether a number is even.

There is more than one way to assign values to \(q\) and \(r\), depending on how integer division is interpreted. The most common mathematical definition computes the mod function as \(n \bmod m = n - m\lfloor n/m\rfloor\). In this case, \(-3 \bmod 5 = 2\). However, Java and C++ compilers typically use the underlying processor’s machine instruction for computing integer arithmetic. On many computers this is done by truncating the resulting fraction, meaning \(n \bmod m = n - m (\mathrm{trunc}(n/m))\). Under this definition, \(-3 \bmod 5 = -3\). Another language might do something different.

Unfortunately, for many applications this is not what the user wants or expects. For example, many hash systems will perform some computation on a record’s key value and then take the result modulo the hash table size. The expectation here would be that the result is a legal index into the hash table, not a negative number. Implementers of hash functions must either ensure that the result of the computation is always positive, or else add the hash table size to the result of the modulo function when that result is negative.

More to Explore

You have attempted of activities on this page