在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
相關用法
- Python now()用法及代碼示例
- Python cmp()用法及代碼示例
- Python map()用法及代碼示例
- Python ord()用法及代碼示例
- Python int()用法及代碼示例
- Python dir()用法及代碼示例
- Python hex()用法及代碼示例
- Python sum()用法及代碼示例
- Python tell()用法及代碼示例
- Python id()用法及代碼示例
- Python oct()用法及代碼示例
注:本文由純淨天空篩選整理自Shivam_k大神的英文原創作品 Python | math.gcd() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。