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 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:
Generically,
Implementation
Let’s take a look at the code:
Press + to interact
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. Examine the illustration below. If a number is divided by , it can give remainders: ...