Easy Tutorial
❮ Python String Expandtabs Python Number ❯

Python Greatest Common Divisor Algorithm

Python3 Examples

The following code is used to implement the greatest common divisor algorithm:

Example (Python 3.0+)

# Filename : test.py
# author by : www.tutorialpro.org

# Define a function
def hcf(x, y):
   """This function returns the greatest common divisor of two numbers"""

   # Get the smaller value
   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

# User inputs two numbers
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

print("The greatest common divisor of", num1, "and", num2, "is", hcf(num1, num2))

Executing the above code outputs:

Enter the first number: 54
Enter the second number: 24
The greatest common divisor of 54 and 24 is 6

Python3 Examples

❮ Python String Expandtabs Python Number ❯