Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I have a function that accepts 2 numbers and to find the least common multiple for those numbers, I will use loop here.

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

In python, Is there any built-in module that does the same work instead of typing a custom function?

1 Answer

0 votes
by (26.4k points)

In the "math" library, we have the Greatest Common Division function. (For Python 3.4 or 2.7, it's covered in fractions instead.) And composing an LCM on top of a GCD is pretty inconsequential: 

def lcm(a, b):

    return abs(a*b) // math.gcd(a, b)

Or then again, in case you're utilizing NumPy, it's accompanied an lcm function for a long while now.

Interested to learn python in detail? Come and Join the python course.

Watch this video tutorial on how to become a professional in python

Browse Categories

...