I am currently using a function that accepts two numbers and uses a loop to find the least common multiple of those numbers,
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
Is there a built-in module in Python that does it instead of writing a custom function?
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) # printing the result for the users. print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2))
lcm() function in Python? The math module in Python contains a number of mathematical operations. Amongst some of the most important functions in this module is the lcm() function which returns the least common multiple of the specified integer arguments. The lcm function was newly introduced in the Python version 3.9.
The least common divisor can be found by calculating the GCD of the given two numbers, once found, the LCD in python can be found by dividing the GCD by the product of the two numbers.
There is no such thing built into the stdlib.
However, there is a Greatest Common Divisor function in the math
library. (For Python 3.4 or 2.7, it's buried in fractions
instead.) And writing an LCM on top of a GCD is pretty trivial:
def lcm(a, b): return abs(a*b) // math.gcd(a, b)
Or, if you're using NumPy, it's come with an lcm
function for quite some time now.
This is available as math.lcm()
. It also takes any length of arguments, allowing you to find the lowest common multiple of more than 2 integers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With