In this example, you’ll get to learn how to find and prints the LCM and HCF of two numbers in Python entered by the user.
This covers the following:
Note: LCM stands for Least Common Multiple. Whereas HCF stands for Highest Common Factor also known as GCD.
To find the LCM of two numbers in Python, you have to ask from user to enter any two numbers, then find and print the LCM value.
print("Enter Two Numbers: ")
num1 = int(input())
num2 = int(input())
if num1 > num2:
lcm = num1
else:
lcm = num2
while True:
if lcm%num1 == 0 and lcm%num2 == 0:
break
else:
lcm = lcm + 1
print("The LCM of {num1} and {num2} = {lcm}")
Here, when the user passes two numbers, 10 as the first number and 25 as the second number by pressing ENTER, then the LCM of 10 and 25 will be printed as 50.
Explanation:
Also, the f-string is a string literal that is used as an f at the beginning and curly braces containing expression that will be replaced with its value.
And, ==(is equal) assignment operator checks if the value of ch is equal to the mentioned value.
Output:
Enter Two Numbers:
10
25
The LCM of 10 and 25 = 50
This program is to find and print the value of HCF or GCD of two numbers entered by user:
print("Enter Two Numbers: ")
num1 = int(input())
num2 = int(input())
if num1>num2:
hcf = num1
else:
hcf = num2
while True:
if num1%hcf==0 and num2%hcf==0:
break
else:
hcf = hcf - 1
print(f"The HCF of {num1} and {num2} = {hcf}")
Here, the process is similar to evaluating LCM.
Output:
Enter Two Numbers:
10
25
The HCF of 10 and 25 = 5
This program uses formula to find and print LCM and HCF both in a single program:
print("Enter Two Numbers: ")
num1 = int(input())
num2 = int(input())
a = num1
b = num2
while b!=0:
temp = b
b = a%b
a = temp
hcf = a
lcm = int((num1*num2)/hcf) # result as int type
print(f"The LCM of {num1} and {num2} = {lcm}")
print(f"The HCF of {num1} and {num2} = {hcf}")
Output:
Enter two numbers:
10
25
The LCM of 10 and 25 = 50
The HCF of 10 and 25 = 5
In this, we discussed how to find LCM and HCF of two numbers using Python programming language using if else statement
, while loop
and formula
.