on
Italy
- Get link
- X
- Other Apps
# 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
# 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))
OutputEnter first number: 54 Enter second number: 24 The L.C.M. of 54 and 24 is 216This program asks for two integers and passes them to a function which returns the L.C.M. In the function, we first determine the greater of the two number since the L.C.M. can only be greater than or equal to the largest number. We then use an infinite
while
loop to
go from that number and beyond. In each iteration, we check if both the
input numbers perfectly divides our number. If so, we store the number
as L.C.M. and break from the loop. Otherwise, the number is incremented
by 1 and the loop continues.Number1 * Number2 = L.C.M. * G.C.D.Here is a Python program to implement this.
# Python program to find the L.C.M. of two input number
# define gcd function
def gcd(x, y):
"""This function implements the Euclidian algorithm
to find G.C.D. of two numbers"""
while(y):
x, y = y, x % y
return x
# define lcm function
def lcm(x, y):
"""This function takes two
integers and returns the L.C.M."""
lcm = (x*y)//gcd(x,y)
return lcm
# 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 output of this program is same as before. We have two functions gcd()
and lcm()
. We require G.C.D. of the numbers to calculate its L.C.M. So, lcm()
calls the function gcd()
to accomplish this. G.C.D. of two numbers can be calculated efficiently
using the Euclidean algorithm. Click here to learn more about methods
to calculate G.C.D in Python.
Comments
Post a Comment