In this post, we are going to find HCF (Highest Common Factor) in Python using a while loop.
The HCF (Highest Common Factor) of two numbers is the largest number that divides both of them.
Here is a program in Python to find the HCF of two numbers using a while loop.
Simple Code:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
i = 1
hcf = 1
while i <= num1 and i <= num2:
if num1 % i == 0 and num2 % i == 0:
hcf = i
i += 1
print("HCF of", num1, "and", num2, "is", hcf)
Output:
Enter first number: 5
Enter second number: 50
HCF of 5 and 50 is 5
Explanation with comments:
# Taking input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
# Initializing variables
i = 1
hcf = 1
# Finding HCF
while i <= num1 and i <= num2:
# Check if i divides both num1 and num2
if num1 % i == 0 and num2 % i == 0:
# If yes, update the hcf
hcf = i
# Increment i
i += 1
# Printing the result
print("HCF of", num1, "and", num2, "is", hcf)
Explanation:
The program takes two numbers as input from the user and initializes a variable ‘i’ to 1 and the HCF to 1.
It then uses a while loop to find the HCF by checking if ‘i’ divides both ‘num1’ and ‘num2’.
If it does, it updates the HCF. Finally, it prints the result.
Note: If both numbers are prime, the HCF will be 1.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.