In mathematics, the LCM (Least Common Multiple) of two or more integers is the smallest positive integer that is a multiple of all given integers.
In Python, we can easily find the LCM of two numbers using a function.
Here’s a Python program to find the LCM of two numbers:
def lcm(a, b): if a > b: greater = a else: greater = b while True: if greater % a == 0 and greater % b == 0: lcm = greater break greater += 1 return lcm num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The LCM of", num1, "and", num2, "is", lcm(num1, num2))
In this program, we define a function lcm
that takes two arguments a
and b
.
We first check which number is greater and assign it to the variable greater
.
We then use a while
loop to check if greater
is a multiple of both a
and b
.
If it is, then we have found the LCM and we break out of the loop.
If it’s not, we increment greater
and continue checking.
We then call the lcm
function with the two numbers entered by the user, and print the result.
For example, if the user enters 4
and 6
, the program will output:
Enter first number: 4 Enter second number: 6 The LCM of 4 and 6 is 12
This program works for any two positive integers, and can be easily modified to find the LCM of more than two integers.