Modulus

In this lesson, we will 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 number. The symbol for mod is %.

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

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

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 take a look at the code:

Press + to interact
def mod(dividend, divisor) :
# Check division by 0
if divisor == 0 :
print("Divisor cannot be ")
return 0
# Base Case
if dividend < divisor :
return dividend
# Recursive Case
else :
return mod(dividend - divisor, divisor)
# Driver Code
print(mod(10, 4))

Explanation:

Let’s discuss how we reached this solution. Examine the illustration below. If a number is divided by 44, it can give 44 remainders: 00 ...