math.gcd(*integers) returns the greatest common divisor of the given integers as a non-negative int.
Added for two integers in Python 3.5, it was extended in Python 3.9 to accept zero, one, or many integer arguments (math.gcd() == 0).
math.gcd() is a function in Python's standard math module: import it with import math and call math.gcd(...), or import the name directly with from math import gcd. Added in Python 3.5 (two args); zero, one, or 3+ args since Python 3.9.
Syntax
Import math and pass two integers (or any count in Python 3.9+).
python
import math
d = math.gcd(a, b)
Call
What it does
math.gcd(12, 18)
Returns 6.
math.gcd(-24, 36)
Returns 12 (always non-negative).
math.gcd(0, 0)
Returns 0.
math.gcd(12.0, 6)
Raises TypeError: floats are rejected.
Notice math.gcd(0, 0) returns 0 rather than raising an error, and negative arguments return a positive divisor. Pairs with math.lcm() (Python 3.9+).
Function signatures
python
math.gcd(*integers)
# 2 args in Python 3.5-3.8; 0, 1, or more args in Python 3.9+
Parameters
Parameter
Description
*integers
Integer values (int only). Passing floats or non-integers raises TypeError.
Return Value
Return Value
Description
int
Non-negative greatest common divisor; 0 if all arguments are 0 (or none given in 3.9+).
Python Examples
Example 1 — Simplify Fractions to Lowest Terms With math.gcd()
Divide numerator and denominator by their GCD using exact floor division //.
python
import math
for num, den in [(12, 18), (100, 75), (-24, 36)]:
g = math.gcd(num, den)
print(f"{num}/{den} -> {num // g}/{den // g} (gcd={g})")