Write a Python Program to find LCM
Least Common Multiple (LCM) in Mathematics:
The Least Common Multiple (LCM) of two or more integers is the smallest positive integer that is divisible by all of the given integers. In other words, it’s the smallest multiple that two or more numbers share.
For example, consider the numbers 3 and 4. The multiples of 3 are 3, 6, 9, 12, 15, … and the multiples of 4 are 4, 8, 12, 16, 20, …. The smallest number that appears in both lists is 12. Therefore, the LCM of 3 and 4 is 12.
To find the LCM of two numbers, you can use the relationship between the LCM and the Greatest Common Divisor (GCD). The formula is:
LCM(a,b)= a⋅b ​/ GCD(a,b)
Where GCD(a,b) is the Greatest Common Divisor of a and b. This relationship allows you to find the LCM by first calculating the GCD of the given numbers and then using it to compute the LCM.
Python Program To Find LCM:
Here’s a Python program that finds the Least Common Multiple (LCM) of two numbers:
def gcd(a, b):
   while b:
       a, b = b, a % b
   return a
def lcm(a, b):
   return (a * b) // gcd(a, b)
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
lcm_result = lcm(num1, num2)
print("LCM of", num1, "and", num2, "is", lcm_result)
Explanation:
- The program defines two functions: gcd() to calculate the Greatest Common Divisor (GCD) of two numbers using the Euclidean algorithm, and lcm() to calculate the LCM of two numbers using the relationship
LCM(a,b)= a⋅b / GCD(a,b)​.
- The user is prompted to enter two numbers using the input() function, and these numbers are converted to integers using the int() function. The input numbers are stored in the variables num1 and num2.
- The program calculates the LCM of the two input numbers by calling the lcm() function and passing num1 and num2 as arguments. The result is stored in the variable lcm_result.
- The print() function is used to display the calculated LCM along with the input numbers.
Output:
Enter first number: 6
Enter second number: 8
LCM of 6 and 8 is 24
In this example, if the user enters 6 and 8, the program calculates the LCM using the lcm() function and displays the result: “LCM of 6 and 8 is 24”.