最高公因子(HCF)也稱為gcd,可以使用math模塊提供的單個函數在python中進行計算,因此可以使任務在許多情況下都更輕鬆。
天真的方法來計算gcd
- 使用遞歸:
- 使用循環
# Python code to demonstrate naive # method to compute gcd ( Loops ) def computeGCD(x, y): if x > y: small = y else: small = x for i in range(1, small+1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd a = 60 b= 48 # prints 12 print ("The gcd of 60 and 48 is:",end="") print (computeGCD(60,48))
輸出:
The gcd of 60 and 48 is:12
- 使用歐幾裏得算法
# Python code to demonstrate naive # method to compute gcd ( Euclidean algo ) def computeGCD(x, y): while(y): x, y = y, x % y return x a = 60 b= 48 # prints 12 print ("The gcd of 60 and 48 is:",end="") print (computeGCD(60,48))
輸出:
The gcd of 60 and 48 is:12
# Python code to demonstrate naive
# method to compute gcd ( recursion )
def hcfnaive(a,b):
if(b==0):
return a
else:
return hcfnaive(b,a%b)
a = 60
b= 48
# prints 12
print ("The gcd of 60 and 48 is:",end="")
print (hcfnaive(60,48))
輸出:
The gcd of 60 and 48 is:12
使用Python的math.gcd()函數
使用gcd()隻需一行就可以計算相同的gcd。
math.gcd( x, y ) 參數: x: Non-negative integer whose gcd has to be computed. y:Non-negative integer whose gcd has to be computed. 返回值: This method will return an absolute/positive integer value after calculating the GCD of given parameters x and y. Exceptions: When Both x and y are 0, function returns 0, If any number is a character , Type error is raised.
# Python code to demonstrate gcd()
# method to compute gcd
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
常見例外
此函數中的一些常見異常是:
- 兩個數字均為0,gcd為0
- 如果隻有一個數字不是數字,則會引發Type Error。
# 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 ("The 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:
運行時錯誤:
Traceback (most recent call last): File "/home/94493cdfb3c8509146254862d12bcc97.py", line 12, in print (math.gcd('a',13)) TypeError:'str' object cannot be interpreted as an integer
相關用法
注:本文由純淨天空篩選整理自 gcd() in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。