📜  Python| math.gcd()函数

📅  最后修改于: 2022-05-13 01:54:47.956000             🧑  作者: Mango

Python| math.gcd()函数

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

代码#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