Skip to content

How to Calculate the Least Common Multiple in Python

The challenge

Write a function that calculates the least common multiple of its arguments; each argument is assumed to be a non-negative integer. In the case that there are no arguments (or the provided array in compiled languages is empty), return 1.

The solution in Python code

Option 1:

from math import gcd def lcm(*args): lcm=1 for x in args: if x!=: lcm=lcm*x//gcd(lcm,x) else: lcm= return lcm
Code language: Python (python)

Option 2:

def lcm(*args): gcd = lambda m,n: m if not n else gcd(n,m%n) return reduce( lambda x, y: x*y/gcd(x, y), args)
Code language: Python (python)

Option 3:

def lcm(*args): args = set(args) if in args: return x = max(args) y = x args.remove(x) while any(x % z for z in args): x += y return x
Code language: Python (python)

Test cases to validate our solution

@test.describe('Example Tests') def example_tests(): test.assert_equals(lcm(2,5),10) test.assert_equals(lcm(2,3,4),12) test.assert_equals(lcm(9),9) test.assert_equals(lcm(),) test.assert_equals(lcm(,1),)
Code language: Python (python)

See also  When your Python code is much faster with PyPy
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x