Built-in module to calculate the least common multiple

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

In Python 3.9+

This is available as math.lcm(). It also takes any number of arguments, allowing you to find the lowest common multiple of more than 2 integers.

For example:

>>> from math import lcm
>>> lcm(2, 5, 7)
70

Solution 3 - Python

Try this instead:

def lcm(x, y):
    from fractions import gcd # or can import gcd from `math` in Python 3
    return x * y // gcd(x, y)

Solution 4 - Python

To simplify your code a little:

def lcm(x, y):
    for currentPossibleLCM in range(max(x,y), (x*y)+1)
         if((currentPossibleLCM % x == 0) and (currentPossibleLCM % y == 0)):
              return currentPossibleLCM

Runtime: O(x*y)

Solution 5 - Python

This is not only for two numbers specifically but for finding LCM of an array of integers. (without using math.lcm())

import math
from functools import reduce

def lcm(arr):

    l=reduce(lambda x,y:(x*y)//math.gcd(x,y),arr)
    return l

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaverickDView Question on Stackoverflow
Solution 1 - PythonabarnertView Answer on Stackoverflow
Solution 2 - PythonOrangutanView Answer on Stackoverflow
Solution 3 - PythonTim PetersView Answer on Stackoverflow
Solution 4 - PythonSatbir KiraView Answer on Stackoverflow
Solution 5 - PythonVinuraView Answer on Stackoverflow