Current location - Recipe Complete Network - Dietary recipes - Greatest common divisor and least common multiple python
Greatest common divisor and least common multiple python

Find the greatest common denominator and least common multiple in python

Define a function

def hcf(x, y):

This function returns the greatest common denominator of two numbers

# Get the minimum 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

# The user enters two numbers

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

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

Finding the There are various algorithms for finding the least common multiple of two numbers, and one of the most efficient is to first calculate their greatest common divisor.

The greatest common divisor of two positive integers can be found by using the method of rolling over and dividing. First save copies of the values of a and b, find the remainder of a ÷ b, and if it is not equal to zero, make a = b and b equal to the remainder this time.

Repeat doing the above division by zero until the remainder is zero when the value of B is the greatest common divisor of the two numbers at the beginning. At this point the initial product of the two numbers divided by the greatest common divisor is the least common multiple of the two numbers.