Home »
Python
math.gcd() method with example in Python
Python math.gcd() method: Here, we are going to learn about the math.gcd() method with example in Python.
Submitted by IncludeHelp, on April 18, 2019
Python math.gcd() method
math.gcd() method is a library method of math module, it is used to find GCD (Greatest Common Divisor) of given numbers, it accepts two integer numbers and returns their greatest common divisor (the largest positive integer that divides both of the numbers).
Note:
 math.gcd() is available in newer version Python 3.5
 If both numbers are 0 – it returns 0.
 If one of the numbers is 0 – it returns another nonzero number.

If anything else like float or string is provided, the method returns a "TypeError",
In the case of float parameter, it returns "TypeError: 'float' object cannot be interpreted as an integer"
In the case of a string parameter, it returns "TypeError: 'str' object cannot be interpreted as an integer"
Syntax of math.gcd() method:
math.gcd(a, b)
Parameter(s): a, b – two integer numbers whose greatest common divisor has to be calculated.
Return value: int – it returns an integer value, which is the GCD (Greatest Common Divisor) i.e. the largest integer number that divided both numbers.
Example:
Input:
a = 10
b = 15
# function call
print(math.gcd(a, b))
Output:
15
Python code to demonstrate example of math.gcd() method
# python code to demonstrate example of
# math.gcd() method
# importing math module
import math
# numbers
a = 10
b = 15
print("gcd is = ", math.gcd(a,b))
a = 10
b = 0
print("gcd is = ", math.gcd(a,b))
a = 0
b = 0
print("gcd is = ", math.gcd(a,b))
Output
gcd is = 5
gcd is = 10
gcd is = 0
TOP Interview Coding Problems/Challenges