Search⌘ K
AI Features

Modulus

Explore the modulus operation and how to implement it recursively within numerical problems. This lesson helps you understand dividing numbers, calculating remainders, and structuring base and recursive cases for modulus in JavaScript recursion, preparing you to handle related coding interview questions.

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:

Javascript (babel-node)
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, 22 ...