If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, you can find the least common multiple (LCM) of two or more numbers using the
math.lcm()
function from themath
module. The LCM is the smallest positive integer that is divisible by all the numbers.Here's an example of how to find the LCM of two numbers:
pythonCopy code
import math def find_lcm(a, b): return math.lcm(a, b) # Example usage: num1 = 12 num2 = 18 lcm_result = find_lcm(num1, num2) print(f"The LCM of {num1} and {num2} is: {lcm_result}")
Output:
csharpCopy code
The LCM of 12 and 18 is: 36
In this example, the
find_lcm()
function takes two numbersa
andb
as input and uses themath.lcm()
function to calculate their LCM. The function returns the LCM as the result.To find the LCM of more than two numbers, you can call the
math.lcm()
function multiple times, passing the result of the previous LCM calculation and the next number as arguments.pythonCopy code
import math def find_lcm(*args): result = args[0] for num in args[1:]: result = math.lcm(result, num) return result # Example usage: num1 = 12 num2 = 18 num3 = 24 lcm_result = find_lcm(num1, num2, num3) print(f"The LCM of {num1}, {num2}, and {num3} is: {lcm_result}")
Output:
csharpCopy code
The LCM of 12, 18, and 24 is: 72
In this example, the
find_lcm()
function uses variable-length arguments (*args
) to accept any number of input arguments. It then iterates through each argument, calculating the LCM one by one and updating the result. The final result is the LCM of all the input numbers.
Comments: 0