首页 > 编程知识 正文

Python 程序:计算两个数的 GCD

时间:2023-11-24 15:33:38 阅读:308829 作者:RHAP

编写一个 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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。