Modulus
In this lesson, we will 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 example:
Mathematical Notation
The above illustration can be mapped on to the following equation:
Generically,
Implementation
Let’s have a look at the code:
def mod(dividend, divisor) :# Check division by 0if divisor == 0 :print("Divisor cannot be ")return 0# Base Caseif dividend < divisor :return dividend# Recursive Caseelse :return mod(dividend - divisor, divisor)# Driver Codeprint(mod(10, 4))
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: , , , and .
Notice that the remainder repeats after every iteration. This means:
We can then generalize this as follows:
We can continue subtracting from until the becomes less than . In this case, the remainder will be the
This mathematical generalization
will be our recursive case, while the condition when the is less than the will be our base case.
Let’s have a look at the sequence of function calls being made:
In the next lesson, we have a problem for you to solve.