Python math.gcd() 方法

Python math.gcd() 方法 Python math 模块

Python math.gcd() 方法返回给定的整数参数的最大公约数。

gcd(0,0) 返回 0。

Python 版本:3.5

在 3.9 版更改: 添加了对任意数量的参数的支持,之前的版本只支持两个参数。

语法

math.gcd() 方法语法如下:

math.gcd(*integers)

参数说明:

  • *integers -- 必需,数字。如果 x 不是一个数字,返回 TypeError。

返回值

返回一个整数 int,表示两个或多个整数的最大公约数 (GCD)。

实例

以下实例返回数字的最大公约数:

实例

# 导入 math 包
importmath

# 输出最大公约数
print(math.gcd(3,6))
print(math.gcd(6,12))
print(math.gcd(12,36))
print(math.gcd(-12, -36))
print(math.gcd(5,12))
print(math.gcd(10,0))
print(math.gcd(0,34))
print(math.gcd(0,0))

输出结果:

3
6
12
12
1
10
34
0

Python math.gcd() 方法 Python math 模块