Python Program to Find LCM and HCF in 2023

0


Python Program to Find LCM and HCF in 2023


Here's a Python program to find the LCM (Least Common Multiple) and HCF (Highest Common Factor) of two numbers:

Here's how it works:

The lcm function takes two integers x and y as arguments.
It finds the greater number among the two.
It then starts a while loop which checks whether the greater number is divisible by both x and y.
If it is, then it returns the LCM.
If not, it increments the greater number by 1 and repeats the process until the LCM is found.
The hcf function takes two integers x and y as arguments.
It finds the smaller number among the two.
It then starts a for loop which checks all the numbers from 1 to the smaller number to see if they divide both x and y.
If a number does, then it updates the HCF variable with that number.
At the end of the loop, it returns the HCF.
The program gets input from the user for two numbers, and then calls the lcm and hcf functions with those numbers as arguments.
Finally, it prints the LCM and HCF.


Input Program For Finding LCM and HCF :


def lcm(x, y):
    """This function takes two integers and returns their LCM."""
    # Find 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

def hcf(x, y):
    """This function takes two integers and returns their HCF."""
    # Find the smaller number
    if x < y:
        smaller = x
    else:
        smaller = y
    
    for i in range(1, smaller+1):
        if x % i == 0 and y % i == 0:
            hcf = i
    
    return hcf

# Get input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Calculate and print LCM
print("The LCM of", num1, "and", num2, "is", lcm(num1, num2))

# Calculate and print HCF
print("The HCF of", num1, "and", num2, "is", hcf(num1, num2))


Output of Program :

Enter first number: 428
Enter second number: 56
The LCM of 428 and 56 is 5992
The HCF of 428 and 56 is 4


Post a Comment

0Comments
Post a Comment (0)