python 计算两个整数的最大公约数和最小公倍数

qzlgjiam  于 2022-11-27  发布在  Python
关注(0)|答案(2)|浏览(152)

我需要编写一个Python程序,用户在其中输入两个数字,并接收这些数字的LCM和HCF。我试过了,我的LCM是正确的,但我的HCF是错误的,所以有人能帮助我找到HCF吗?谢谢!

num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
def compute_lcm(x, y):

   # choose the greater number
   if x > y:
       greater = x
   else:
       greater = y

   while(True):
       if((greater % x == 0) and (greater % y == 0)):
           lcm = greater
           break
       greater += 1

   return lcm
print("The L.C.M. is", compute_lcm(num1, num2))
7xllpg7q

7xllpg7q1#

如果你想找到最大公约数或最大公因子(HCF),你可以使用欧几里德算法:这是article in FreeCodeCamp.org的链接
下面是你可以在你的案例中使用的python代码:

"""  
finding HCF
"""

def hcfLoop(x : int, y : int) -> int:
    """  
    finding hinghest common factor using loop
    returns int
    """
    while (x % y) > 0:
        remainder = x % y
        x = y
        y = remainder
    
    return y

def hcfRecurs(x : int, y : int) -> int:
    """  
    find highest common factor using recursion
    """
    if y == 0 :
        return x
    else:
        return hcfRecurs(y, x % y)

x = 1220
y = 516
print(f"the HCF for {x} and {y} using loop: {hcfLoop(x,y)}")
print(f"the HCF for {x} and {y} using recursion: {hcfRecurs(x,y)}")

的回答:

the HCF for 1220 and 516 using loop: 4
the HCF for 1220 and 516 using recursion: 4
xzv2uavs

xzv2uavs2#

num1 = 36
num2 = 60
hcf = 1

for i in range(1, min(num1, num2)):
    if num1 % i == 0 and num2 % i == 0:
        hcf = i
print("Hcf of", num1, "and", num2, "is", hcf)
# HCF of 36 and 60 is 12

相关问题