Modulus
In this lesson, we'll learn about the modulo operation and how to implement it using recursion.
We'll cover the following...
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.
Mathematical Notation
The above illustration can be mapped on to the following equation:
Generically,
Implementation
Let’s have a look at the code:
Press + to interact
function mod(dividend, divisor) {// Check division by 0if (divisor == 0) {console.log("Divisor cannot be ")return 0;}// Base caseif (dividend < divisor) {return dividend;}// Recursive caseelse {return mod(dividend - divisor, divisor);}}// Driver Codevar 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 , it can give remainders: , , ...
Access this course and 1400+ top-rated courses and projects.