Python math.gcd() - Greatest Common Divisor
Python math.gcd()
math.gcd(*integers) function returns the Greatest Common Divisor (GCD) of the integers passed as arguments.
Syntax
The syntax to call gcd() function is
math.gcd(*integers)
where
Parameter | Required | Description |
---|---|---|
*integers | No | None, one or multiple integer values. |
If no integer value is passed as argument to gcd(), then the return value is 0.
If only one integer is passed to gcd(), then then same value is returned as GCD.
If any non-integral value is passed as argument to gcd(), then the function raises TypeError.
Examples
1. Find GCD of two integers
In the following program, we take two integers: 10 and 25, and find their GCD using math.gcd() function.
Python Program
import math
result = math.gcd(10, 25)
print('gcd() :', result)
Output
gcd() : 5
2. Find GCD of a single integer value
In the following program, we take only one integer: 10, and find its GCD using math.gcd() function.
Python Program
import math
result = math.gcd(25)
print('gcd() :', result)
Output
gcd() : 25
3. Find GCD of float values
In the following program, we take two float values: 25.5 and 2.6, and find their GCD using math.gcd() function. gcd() throws TypeError if the arguments are of type float.
Python Program
import math
result = math.gcd(25.5, 2.6)
print('gcd() :', result)
Output
TypeError: 'float' object cannot be interpreted as an integer
Summary
In this Python Math tutorial, we learned the syntax of, and examples for math.gcd() function.