# Introduction to Modulus

When we divide two integer numbers we will have an equation that looks like the following:

A/B = Q Remainder R where

A is the dividend

B is the divisor

Q is the quotient

R is the remainder

Sometimes, we are only interested in what the remainder is when we divide A by B. For these cases there is an operator called modulo operator (abbreviated as mod).

Using the same A, B, Q, and R as above, we would have: A mod B = R.

We would say this as A modulo B is equal to R where B is referred to as the modulus.

There are multiple uses of modulus operator such as telling if a number is a factor of another number or not. It can also be used to generate a random number or finding an even or odd number as well.

# C++ Modulus Operator

Taking a simple arithmetic problem as shown above, how would you compute this in a programming language such as C or C++? The C and C++ language provides a built-in mechanism, the modulus operator (‘%’), that computes the remainder that results from performing integer division. Consider the following program which takes a number from user and calculates the remainder of the number with divided by 3.

1 2 3 4 5 6 7 8 |
#include <iostream> using namespace std; int main() { int num; cin >> num; return num % 3; } |

Take another example below which calculates whether the input number is leap year and returns 1 otherwise return 0.

1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> using namespace std; int main() { int nCentury; cin >> nCentury; if ((nCentury % 4) == 0) { return 1; } return 0; } |

You may also find if a number or odd or even by using modulus operator. You can do this by asking for the remainder of the number when divided by 2.

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> using namespace std; int main() { int evenNum; cin >> evenNum; if (evenNum % 2 == 0 ) { cout << evenNum << " is even "; } return 0; } |

# std::modulus

The C++ standard library provides a specialization of std::modulus when T is not specified, which leaves the parameter types and return type to be deduced. Binary function object class whose call returns the result of the modulus operation between its two arguments (as returned by operator %). For example, the following C++ code find whether the number in an array is even or odd by using the modulus.

1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> // std::cout #include <functional> // std::modulus, std::bind2nd #include <algorithm> // std::transform int main () { int numbers[]={1,2,3,4,5}; int remainders[5]; std::transform (numbers, numbers+5, remainders, std::bind2nd(std::modulus<int>(),2)); for (int i=0; i<5; i++) std::cout << numbers[i] << " is " << (remainders[i]==0?"even":"odd") << '\n'; return 0; } |

1 2 3 4 5 6 |
Output: 1 is odd 2 is even 3 is odd 4 is even 5 is odd |

The following video tutorials also shows Integer division and remainders using the modulus (%) operator.