Calculating the Greatest Common Divisor (GCD)
The following code demonstrates how to compute the Greatest Common Divisor (GCD) using Python:
Example
# Define a function def hcf(x, y): """This function returns the Greatest Common Divisor of two numbers""" # Get the smaller of the two values if x > y: smaller = y else: smaller = x for i in range(1, smaller + 1): if (x % i == 0) and (y % i == 0): hcf = i return hcf # Get user input for two numbers num1 = int(input("Enter the first number: ")) num2 = int(input("Enter the second number: ")) print(num1, "and", num2, "have a Greatest Common Divisor of", hcf(num1, num2))
Example Output:
Enter the first number: 54 Enter the second number: 24 54 and 24 have a Greatest Common Divisor of 6