Modulus

In this lesson, we'll learn about the modulo operation and how to implement it using recursion.

What is the modulo operation?

The modulo operation (abbreviated as mod) returns the remainder when a number is divided by another. The symbol for mod is %.

The number being divided is called the dividend, and the number that divides is called the divisor.

The illustration below represents the concept of remainders using basic division:

Basic division.
Basic division.

Mathematical Notation

The above illustration can be mapped on to the following equation:

43+2=144 * 3 + 2 = 14

Generically, (divisorquotient)+remainder=dividend(divisor * quotient) + remainder = dividend

Implementation

Let’s have a look at the code:

Press + to interact
function mod(dividend, divisor) {
// Check division by 0
if (divisor == 0) {
console.log("Divisor cannot be ")
return 0;
}
// Base case
if (dividend < divisor) {
return dividend;
}
// Recursive case
else {
return mod(dividend - divisor, divisor);
}
}
// Driver Code
var dividend = 10;
var divisor = 4;
console.log(mod(dividend, divisor));

Explanation:

Let’s discuss how we reached this solution. Look at the illustration below. It shows that if a number is divided by 44, it can give 44 remainders: 00, 11, ...

Access this course and 1400+ top-rated courses and projects.