divmod() in Python and its application


The divmod() is part of python’s standard library which takes two numbers as parameters and gives the quotient and remainder of their division as a tuple. It is useful in many mathematical applications like checking for divisibility of numbers and establishing if a number is prime or not.

Syntax

Syntax: divmod(a, b)
a and b : b divides a
a and b are integers or floats

Examples

In the below example see the cases of both integers and floats. On the application of divmod() they give us a resulting tuple which is can also contain integers and float values.

# with integers
print("5 and 2 give:",divmod(5,2))
print("25 and 5 give:",divmod(25,5))

# with Floats
print("5.6 and 2 give:",divmod(5.6,2))
print("11.3 and 9.2 give:",divmod(11.3,9.2))

Output

Running the above code gives us the following result −

5 and 2 give: (2, 1)
25 and 5 give: (5, 0)
5.6 and 2 give: (2.0, 1.5999999999999996)
11.3 and 9.2 give: (1.0, 2.1000000000000014)

Using Zero

If the first argument is zero then we get (0,0). And If the second argument is zero then we get Zerodivision error as expected.

Example

# With first argument as zero
print("0 and 8 give:",divmod(0,8))

# With second argument as zero
print("8 and 0 give:",divmod(8,0))

Output

Running the above code gives us the following result −

0 and 8 give: (0, 0)
Traceback (most recent call last):
File "xxx.py", line 6, in
print("8 and 0 give:",divmod(8,0))
ZeroDivisionError: integer division or modulo by zero

Checking divisibility

If the second value of the tuple after division is 0 then we say that the first number is divisible by second. Else it is not divisible. The below example illustrates this.

Example

m = 12
n = 4
quotient,remainder = divmod(m,n)
print(quotient)
print(remainder)
if (remainder==0):
   print(m,' is divisible by ',n)
else:
   print(m,' is not divisible by ',n)

Output

Running the above code gives us the following result −

3
0
12 is divisible by 4

Checking if Number is Prime

We can use divmod() to keep track of the reminders it generates when we start dividing a number by each number starting with itself till 1. For a prime number the count of zero remainder will be only one as no number other than itself will divide it perfectly. If the count of zero remainder is greater than 1 then the number is not prime,.

Example

num = 11
a = num
# counter the number of remainders with value zero
count = 0
while a != 0:
   q, r = divmod(num, a)
   a -= 1
   if r == 0:
      count += 1
if count > 2:
   print(num, 'is not Prime')
else:
   print(num, 'is Prime')

Output

Running the above code gives us the following result −

11 is Prime

Updated on: 07-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements