Calculate the Lcm of a List of Given Numbers in Python

Calculate the LCM of a list of given numbers in Python

As of Python 3.9 lcm() function has been added in the math library. It can be called with the following signature:

math.lcm(*integers)

Return the least common multiple of the specified integer arguments.
If all arguments are nonzero, then the returned value is the smallest
positive integer that is a multiple of all arguments. If any of the
arguments is zero, then the returned value is 0. lcm() without
arguments returns 1.

Advantages:

  1. Besides being native,
  2. Its a one-liner,
  3. Its fastest,
  4. Can deal with arbitrarily long list of integers
  5. And can deal with nearly any kind of exceptions (e.g. lcm(0,0)) overlooked by custom-built solutions.

Updated: Finding the least common multiple of a list of numbers in python

This could be one of the approach.

numbers=list(map(int,input().split()))
numbers.sort()
maximum=numbers[0] #gcd of the input numbers cannot be greater than minimum number in the list.Therefore we are retrieving the mininum number of the list.
gcd=1 #Initial value of gcd.
for i in range(1,(maximum+1)):
flag=0
for j in range(len(numbers)):
num=numbers[j]
if num % i ==0: #check if the every number in the input is divisible by the value of i
flag=1 #if divisible set flag=1 and then check the other numbers of the input.
else:
flag=0 #if any of the number of the input is not divisible then flag =0 and go to next iteration of i.
break
if flag==1:
gcd=i #if flag=1 that means every number of the input is divisible by the value of j.Update the value of gcd.

print(gcd)

That can be done in the following way:

for i in num_factors:
d={}
for j in i:

try:
d[j]=d[j]+1
except KeyError:
d[j]=1

dictionary_copy = d.copy()
a_list.append(dictionary_copy)
print(a_list)
return num_factors

Find the LCM for up to 5 numbers

Maybe something like this, might be suitable for your purposes:

from functools import reduce
from math import gcd

x = []
while len(x) < 2 and len(x) <= 5: # Using this condition removes unneccesary break code:
x = [int(i) for i in input('\nEnter two to five numbers separated by commas: ').split(',')]
if x[0] == 0:
print('\nNo zeroes.')
if len(x) > 5:
print('\nDon\'t enter more than five numbers.')
if len(x) < 2:
x.append(int(input('\nTwo numbers are needed. Enter one more: ')))

lcm = reduce(lambda x, y: x * y // gcd(x, y), x) # lcm = x * y / gcd(x, y)
print(lcm)

When run this prints the lcm, of the 5 inputted numbers.

Enter two to five numbers separated by commas: 1, 2, 3, 4, 5
60

find out the lcm of 2 numbers using Python

# defining a function to calculate LCM  
def calculate_lcm(x, y):
# selecting 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

# taking input from users
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))

Not sure but it might help and this question is repeated many times.

Built-in module to calculate the least common multiple

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.

Least common multiple for 3 or more numbers

You can compute the LCM of more than two numbers by iteratively computing the LCM of two numbers, i.e.

lcm(a,b,c) = lcm(a,lcm(b,c))

Finding the LCM of a range of numbers

This problem is interesting because it doesn't require you to find the LCM of an arbitrary set of numbers, you're given a consecutive range. You can use a variation of the Sieve of Eratosthenes to find the answer.

def RangeLCM(first, last):
factors = range(first, last+1)
for i in range(0, len(factors)):
if factors[i] != 1:
n = first + i
for j in range(2*n, last+1, n):
factors[j-first] = factors[j-first] / factors[i]
return reduce(lambda a,b: a*b, factors, 1)


Edit: A recent upvote made me re-examine this answer which is over 3 years old. My first observation is that I would have written it a little differently today, using enumerate for example. A couple of small changes were necessary to make it compatible with Python 3.

The second observation is that this algorithm only works if the start of the range is 2 or less, because it doesn't try to sieve out the common factors below the start of the range. For example, RangeLCM(10, 12) returns 1320 instead of the correct 660.

The third observation is that nobody attempted to time this answer against any other answers. My gut said that this would improve over a brute force LCM solution as the range got larger. Testing proved my gut correct, at least this once.

Since the algorithm doesn't work for arbitrary ranges, I rewrote it to assume that the range starts at 1. I removed the call to reduce at the end, as it was easier to compute the result as the factors were generated. I believe the new version of the function is both more correct and easier to understand.

def RangeLCM2(last):
factors = list(range(last+1))
result = 1
for n in range(last+1):
if factors[n] > 1:
result *= factors[n]
for j in range(2*n, last+1, n):
factors[j] //= factors[n]
return result

Here are some timing comparisons against the original and the solution proposed by Joe Bebel which is called RangeEuclid in my tests.

>>> t=timeit.timeit
>>> t('RangeLCM.RangeLCM(1, 20)', 'import RangeLCM')
17.999292996735676
>>> t('RangeLCM.RangeEuclid(1, 20)', 'import RangeLCM')
11.199833288867922
>>> t('RangeLCM.RangeLCM2(20)', 'import RangeLCM')
14.256165588084514
>>> t('RangeLCM.RangeLCM(1, 100)', 'import RangeLCM')
93.34979585394194
>>> t('RangeLCM.RangeEuclid(1, 100)', 'import RangeLCM')
109.25695507389901
>>> t('RangeLCM.RangeLCM2(100)', 'import RangeLCM')
66.09684505991709

For the range of 1 to 20 given in the question, Euclid's algorithm beats out both my old and new answers. For the range of 1 to 100 you can see the sieve-based algorithm pull ahead, especially the optimized version.



Related Topics



Leave a reply



Submit