python中math库中的gcd_Python math.gcd()用法及代码示例

在Python中,数学模块包含许多数学运算,可以使用该模块轻松执行。math.gcd()函数计算其参数中提到的2个数的最大公约数。

用法: math.gcd(x, y)

参数:

x:必须计算其gcd的非负整数。

y:必须计算其gcd的非负整数。

返回:计算给定参数x和y的GCD后的绝对/正整数值。

异常:当x和y均为0时,函数返回0,如果任何数字为字符,则会引发Type错误。

代码1:

# Python code to demonstrate the working of gcd()

# importing "math" for mathematical operations

import math

# prints 12

print ("The gcd of 60 and 48 is:", end ="")

print (math.gcd(60, 48))

输出:

The gcd of 60 and 48 is:12

代码2:

# Python code to demonstrate the working of gcd()

# importing "math" for mathematical operations

import math

# prints gcd of x, y

print ("math.gcd(44, 12):", math.gcd(44, 12))

print ("math.gcd(69, 23):", math.gcd(65, 45))

输出:

math.gcd(44, 12): 4

math.gcd(69, 23): 5

代码3:解释异常。

# Python code to demonstrate gcd()

# method exceptions

import math

# prints 0

print ("The gcd of 0 and 0 is:", end ="")

print (math.gcd(0, 0))

# Produces error

print ("\nThe gcd of a and 13 is:", end ="")

print (math.gcd('a', 13))

输出:

The gcd of 0 and 0 is:0

The gcd of a and 13 is:

TypeError:'str' object cannot be interpreted as an integer

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值