Python Program - Find HCF or GCD
Here's a Python program to find the HCF (Highest Common Factor) or GCD (Greatest Common Divisor) of two numbers:
refer ot:theitroad.comdef calculate_hcf(x, y):
"""
Calculates the HCF/GCD of two numbers.
Args:
x: The first number.
y: The second number.
Returns:
The HCF/GCD of the two numbers.
"""
# Determine the smaller number
if x > y:
smaller = y
else:
smaller = x
# Find the factors of the smaller number and check if they divide both numbers
for i in range(1, smaller + 1):
if ((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
# Example usage:
num1 = 54
num2 = 24
print("The HCF of", num1, "and", num2, "is", calculate_hcf(num1, num2)) # Output: The HCF of 54 and 24 is 6
In this program, we define a function called calculate_hcf() that takes two numbers as its arguments, and returns their HCF/GCD.
Inside the function, we determine the smaller number between the two input numbers using an if-else statement. We then use a for loop to iterate over the factors of the smaller number, checking if each factor divides both numbers. If a factor is found, we store it in a variable called hcf.
Finally, we return the value of hcf.
In the example usage, we calculate the HCF of two numbers (54 and 24) using the calculate_hcf() function, and print it out using the print() function.
