Write a program to Find LCM in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Python Program to find the L.C.M. of two input number # define a function def lcm(x, y): """This function takes two integers and returns the L.C.M.""" # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm #to take input from the user num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2)) |
The program defines a function lcm(x, y)
that takes two numbers as arguments and returns their LCM. The function starts by determining which of the two numbers is greater and assigns it to the variable greater
. Then, the function uses a while loop to iterate until it finds a number that is both a multiple of x
and y
.
In each iteration, the function checks if the current greater
number is a common multiple of both x
and y
by using the modulo operator (%
) to check if the remainder of both greater
divided by x
and greater
divided by y
is zero. If both conditions are true, the current number is assigned to the variable lcm
and the loop is broken.
Finally, the function returns the value of lcm
.
The main program then prompts the user to enter two numbers and assigns them to the variables num1
and num2
. Then it calls the lcm(num1, num2)
function and prints out the LCM of the two numbers entered.
For example, if the user enters the numbers 15
and 50
, the output would be: