Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Built-in module to calculate the least common multiple

Tags:

python

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?

like image 512
MaverickD Avatar asked Aug 06 '18 23:08

MaverickD


People also ask

How do you find the LCM using the math module in Python?

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))

Is there an LCM function in Python?

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.

How do you find the LCD in Python?

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.


2 Answers

In Python 3.8 and earlier

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.

like image 163
abarnert Avatar answered Sep 26 '22 00:09

abarnert


In Python 3.9+

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.

like image 22
Orangutan Avatar answered Sep 26 '22 00:09

Orangutan