編寫一個 Python 程序,使用 While 循環、函數和遞歸來查找兩個數的 GCD。要在 Python 中找到 GCD 或 HCF,我們必須至少傳遞一個非零值
最大公約數也被稱為最高公因數,或最大公約數,或最高公約數(HCD),或最大公約數。
在數學中,兩個或兩個以上整數的最大公約數(GCD)是給定整數值除以沒有餘數的最大正整數。例如,整數 8 和 12 的 GCD 值為 4,因為 8 和 12 都可以被 1、2 和 4 整除(餘數為 0),其中最大的正整數為 4。
Python 程序查找兩個數的 GCD 示例 1
這個 python 程序允許用戶輸入兩個正整數值。接下來,我們使用 Python While 循環來限制 I 值不超過用戶指定的值。
在 Python While 循環中,我們使用 If 語句來檢查%i 和% i 餘數是否等於零。如果為真,則最高公因數= 1,否則跳過該值。
# Python Program to find GCD of Two Numbers
a = float(input(" Please Enter the First Value a: "))
b = float(input(" Please Enter the Second Value b: "))
i = 1
while(i <= a and i <= b):
if(a % i == 0 and b % i == 0):
val = i
i = i + 1
print("\n HCF of {0} and {1} = {2}".format(a, b, val))
Please Enter the First Value a: 8
Please Enter the Second Value b: 12
HCF of 8.0 and 12.0 = 4
Python 程序查找兩個數的 HCF 示例 2
這是另一種求兩個數最大公因數的方法。在這個 python 程序中,我們使用 Temp 變量來查找 GCD。
num1 = float(input(" Please Enter the First : "))
num2 = float(input(" Please Enter the Second : "))
a = num1
b = num2
while(num2 != 0):
temp = num2
num2 = num1 % num2
num1 = temp
hcf = num1
print("\n HCF of {0} and {1} = {2}".format(a, b, hcf))
Please Enter the First : 12
Please Enter the Second : 36
HCF of 12.0 and 36.0 = 12.0
Python 程序不用 Temp 就能找到兩個數的 GCD
在這個程序中,我們在不使用 Temp 變量的情況下找到了 GCD。
num1 = float(input(" Please Enter the First : "))
num2 = float(input(" Please Enter the Second : "))
a = num1
b = num2
if(num1 == 0):
print("\n HCF of {0} and {1} = {2}".format(a, b, b))
while(num2 != 0):
if(num1 > num2):
num1 = num1 - num2
else:
num2 = num2 - num1
hcf = num1
print("\n HCF of {0} and {1} = {2}".format(a, b, hcf))
Please Enter the First : 75
Please Enter the Second : 255
HCF of 75.0 and 255.0 = 15.0
用函數求兩個數的 GCD 的 Python 程序
這個 Python 程序同上。然而,我們使用功能 來分離邏輯
def findgcd(num1, num2):
if(num1 == 0):
print("\n HCF of {0} and {1} = {2}".format(a, b, b))
while(num2 != 0):
if(num1 > num2):
num1 = num1 - num2
else:
num2 = num2 - num1
return num1
a = float(input(" Please Enter the First Value a: "))
b = float(input(" Please Enter the Second Value b: "))
gcd = findgcd(a, b)
print("\n HCF of {0} and {1} = {2}".format(a, b, gcd))
用遞歸法計算兩個數的 GCD 的 Python 程序
它允許用戶輸入兩個正整數值,並通過遞歸調用 findGreatestCD 函數來計算這兩個值的最大公約數。
def findGreatestCD(a, b):
if(b == 0):
return a;
else:
return findGreatestCD(b, a % b)
num1 = float(input(" Please Enter the First Value Num1 : "))
num2 = float(input(" Please Enter the Second Value Num2 : "))
Val = findGreatestCD(num1, num2)
print("\n GCD of {0} and {1} = {2}".format(num1, num2, Val))
Please Enter the First Value Num1 : 22
Please Enter the Second Value Num2 : 88
GCD of 22.0 and 88.0 = 22.0
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/290918.html