Python Glossary Русский

Python 3.5+mathterm

math.gcd

combinatorics

Returns the greatest common divisor of two or more integers. math.gcd(48, 36) → 12. Python 3.9+: several arguments at once.

Syntax

math.gcd(*integers)

The result is always non-negative and the signs of the arguments are irrelevant; the gcd of 0 and x is abs(x), and calling it with no arguments at all yields 0. That makes 0 a natural starting value when folding a list with functools.reduce, with no special cases needed. Before Python 3.9 the function took exactly two arguments, so a multi-argument call breaks on older interpreters.

Examples

# Python 3.9+
import math
print(math.gcd(12, 8))    # → 4
print(math.gcd(100, 75))  # → 25
print(math.gcd(0, 5))     # → 5
print(math.gcd(7, 13))    # → 1 (взаимно просты)
print(math.gcd(12, 18, 24))  # → 6 (Python 3.9+)
print(math.gcd(48, 64))   # → 16

See also

Open in the full glossarydocs.python.orgReport an inaccuracy