当前位置:首页 > python教程 > python进阶

Python math.gcd() 方法

python math.gcd() 方法

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

gcd(0,0) 返回 0。

python 版本:3.5

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

语法

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

math.gcd(*integers)

参数说明:

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

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

实例

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

实例

# 导入 math 包
import math

# 输出最大公约数
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


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!