How do you find the least common multiple of a list in python?

I have written a code to find out the LCM (Lowest Common Multiple) of a list of numbers but there appears to be an error in my code. The code is given below:

def final_lcm(thelist):
   previous_thelist = thelist
   prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist))
   factors = 1
   for i in prime_thelist:
       factors = factors*i
   new_thelist = returns_new_thelist(previous_thelist)
   for i in range(1, 10000000000):
       s_empty = []
       for j in new_thelist:
           if i % j  == 0:
               s_empty.append(True)
       if len(new_thelist) == len(s_empty):
           initial_lcm = i
           break
   final_lcm = factor*initial_lcm
   return final_lcm



def returns_new_thelist(ll):
    if 3 in ll:
        ll.remove(3)
    for i in ll:
        if checks_if_prime(i) == True:
            ll.remove(i)
    return ll    

def checks_if_prime(n):
    if n == 2:
    return True
    import math
    for i in range(math.ceil(0.5*n), 1, -1):
        if n % i == 0:
            return False
        elif i == 2:
            return True

print(final_lcm([1,2,3,4,5,6,7,8,9]))

Kindly pardon my poor choice of variables, I request you to see if the logic is correct and that the code is functional.

The syntax error which I am getting is that "factors" is invalid syntax though I don't agree with this. Please tell me where my code is wrong.

How do you find the least common multiple of a list in python?

asked May 15, 2016 at 11:52

How do you find the least common multiple of a list in python?

Aradhye AgarwalAradhye Agarwal

3791 gold badge2 silver badges9 bronze badges

3

This is the best way that I know of :

from math import gcd
a = [100, 200, 150]   #will work for an int array of any length
lcm = 1
for i in a:
    lcm = lcm*i//gcd(lcm, i)
print(lcm)

Hope this helps. All queries, contributions and comments are welcome :)

answered Feb 26, 2017 at 19:01

Ananay MitalAnanay Mital

1,3451 gold badge11 silver badges16 bronze badges

7

Works with an arbitrarily long denominator list.

from math import gcd # Python versions 3.5 and above
#from fractions import gcd # Python versions below 3.5
from functools import reduce # Python version 3.x

def lcm(denominators):
    return reduce(lambda a,b: a*b // gcd(a,b), denominators)

Example:

>>> lcm([100, 200, 300])
600

answered Apr 13, 2018 at 11:34

How do you find the least common multiple of a list in python?

TakingItCasualTakingItCasual

6911 gold badge6 silver badges21 bronze badges

1

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.

answered Jun 17, 2020 at 11:05

In Numpy v1.17 (which is, as of writing, the non-release development version) there is an lcm function that can be used for two numbers with, e.g.:

import numpy as np
np.lcm(12, 20)

or for multiple numbers with, e.g.:

np.lcm.reduce([40, 12, 20])

There's also a gcd function.

answered Feb 8, 2019 at 17:09

Matt PitkinMatt Pitkin

1,57212 silver badges22 bronze badges

3

Your solution might be too lengthy ... Try this !

from functools import reduce    # need this line if you're using Python3.x

def lcm(a, b):
    if a > b:
        greater = a
    else:
        greater = b

    while True:
        if greater % a == 0 and greater % b == 0:
            lcm = greater
            break
        greater += 1

    return lcm

def get_lcm_for(your_list):
    return reduce(lambda x, y: lcm(x, y), your_list)

ans = get_lcm_for([1, 2, 3, 4, 5, 6, 7, 8, 9])
print(ans)

answered May 15, 2016 at 12:11

Jay PatelJay Patel

5201 gold badge3 silver badges14 bronze badges

2

if you don't want to import anything.

def gcd(n, m):
    if m == 0:
        return n
    return gcd(m, n % m)

A = [10, 25, 37, 15, 75, 12]

lcm = 1
for i in A:
    lcm = lcm * i // gcd(lcm, i)
    
print(lcm)

answered Apr 22, 2021 at 6:14

How do you find the least common multiple of a list in python?

SabaSaba

3421 silver badge11 bronze badges

You're missing a closing parenthesis ()) in the third line. Hence the error in line factors.

Moreover in second to last line of your first function, you've named the variable factor instead of factors.

How do you find the least common multiple of a list in python?

SiHa

7,09312 gold badges32 silver badges42 bronze badges

answered May 15, 2016 at 11:57

Jay PatelJay Patel

5201 gold badge3 silver badges14 bronze badges

To find LCM of given list of numbers

def findDivisor(num):
    # 2,3 are the most common divisor for many numbers hence I go by divisor of 2,3
    # if not then by the same number as divisor
    if num%2 == 0:
        return 2
    elif num%3==0:
        return 3
    return num

def findLCM(lcmArray):
    lcm = 1
    while len(lcmArray) > 0:
        minOfLCMArray = min(lcmArray)
        divisor = findDivisor(minOfLCMArray)        

        for x in xrange(0, len(lcmArray)):
            Quotient = lcmArray[x]/divisor
            Reminder = lcmArray[x]%divisor
            if Reminder == 0:
                lcmArray[x] = Quotient

        lcm*=divisor
        minOfLCMArray = min(lcmArray)
        if minOfLCMArray == 1:
            lcmArray.remove(minOfLCMArray)
    return lcm

lcmArray = map(int, raw_input().split())
print findLCM(lcmArray)

answered May 8, 2017 at 10:19

A faster approach without using any math functions would be to calculate GCD and calculate LCM.

def gcd(a,b):
    while b:
        a,b = b, a%b
    return a

Now find LCM using GCF

def lcm(a,b):
    return a*b // gcd(a,b)

Extend this to work with list as below

LCM = functools.reduce(lambda x, y: lcm(x, y), your_list_to_find_lcm)

answered Jul 26, 2018 at 0:20

YashwanthYashwanth

1661 silver badge9 bronze badges

I had written a code to find lcm of numbers within a list. The User can input any number of values he wants. I'm attaching the code below, It is simpler than the code you posted. Try checking this... I know your question is to find errors in your code, but try checking this for future purpose.

a = list(map(int,input('enter numbers for the lcm: ').strip().split()))
a.sort(reverse = True)
a
x = a[0]

while 1:
    sum = 0
    for i in a:
        if x%i == 0:
            sum += 1
    if sum == len(a):
        break
    else :
        x += 1
print(x,' is the lcm of numbers in the input')

How do you find the least common multiple of a list in python?

Harsha pps

1,8242 gold badges23 silver badges34 bronze badges

answered Jul 22, 2019 at 17:48

How do you find the least common multiple of a list in python?

c=1
i=0
q=0
j=2;
flag=0;
count=0;
a=input("ente 3 no")


a=a.split(',')
print(len(a))
for i in range(len(a)):
    z=int(a[i])
    c=c*z

while(j

answered Jul 30, 2018 at 18:14

How do you find the least common multiple of a list in python?

1

Find LCM and GCD of a list of numbers

After reading all these solutions it is still unclear so, here is my possible simplest approach :)

find LCM using GCD

from fractions import gcd
from functools import reduce
a = [2,4] #given list
def LCM(a, b):
    return (a*b)//gcd(a,b) # as LCM(a,b)*GCD(a,b) = a*b
lcm = reduce(LCM, a) #here reduce will iterate through all 
                     #the elements one by one
gcd = reduce(gcd, a)

print(lcm, gcd)

OUTPUT:

4 2

answered Jan 29, 2019 at 11:42

How do you find the least common multiple of a list in python?

ssp4allssp4all

3782 silver badges11 bronze badges

if you do not wish to use GCD algorithm, below code returns the smallest multiple of the greatest number of the array:

            a=[5,10,15,7]
            ctr=1
            LCM=max(a)
            remList=[LCM%i for i in a]
            if all(v == 0 for v in remList):
                    print("LCM is : ", max(a))
            else:
                while True:
                    remList=[LCM%i for i in a]
                    if all(v == 0 for v in remList):
                        print("LCM is : ",LCM)
                        break
                    else:
                       LCM=LCM+max(a)

answered May 10, 2019 at 9:38

This may be useful to you, Rather finding LCM directly, it is a bit simpler to derive LCM from GCD. 

def gcd(a,b):
  if a == 0:
    return b
return gcd(b % a, a)
    
    
x=int(input("enter x"))
y=int(input("enter y"))
    
print(int(gcd(x,y)))
print(int((x*y)/gcd(x,y)))

Anurag

98010 silver badges30 bronze badges

answered Sep 7, 2020 at 5:41

How do you find the least common multiple of a list in python?

prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist))

You're missing a bracket at the end of the line. Correct it to the following:

prime_thelist = list(set(thelist) - set(returns_new_thelist(previous_thelist)))

Also,

if n == 2:
return True

You need to indent the return statement because it is inside a conditional statement.

And it is generally best practice to import any libraries you might need at the beginning rather than in the middle of a function.

answered Sep 20, 2020 at 18:17

How do you find the least common multiple of a list in python?

Dhyey ShahDhyey Shah

253 silver badges6 bronze badges

from math import gcd
a = [100, 200, 150]   #will work for an int array of any length
lcm = a[0]
for i in a[1:]:
    lcm = lcm*i//gcd(lcm, i)  
print lcm

answered Oct 27, 2020 at 6:04

How do you find the least common multiple of a list in python?

I needed a 0 dependency one for python2.7 so I came up with this brute one:

def lcm(lst):
    """
    finds the lcm for the numbers in the list
    """

    candidate = max(lst)

    while True:
    
        if sum([candidate % i == 0 for i in lst]) == len(lst):
             return candidate

        candidate+=1

How do you find the least common multiple of a list in python?

Emi OB

2,4133 gold badges10 silver badges25 bronze badges

answered May 23 at 3:16

LCM for N numbers without using GCD

n=list(map(int,input().split()))
def LCMof2(n1,n2):
  m= max(n1,n2)
  while(1):
    if (m%n1==0 and m%n2==0):
      ans=m
      break
    m+=1
  return ans
lcm1=LCMof2(n[0],n[1])
for i in range(2,len(n)):
  ans=LCMof2(lcm1,n[i])
  lcm1=ans 
print(ans)

answered Aug 9 at 18:38

How do you find the least common multiple of a list in python?

1

This is my answer to compute GCD and LCM. Please try it. Easiest one I could do.

import math
GCF = yourlist[0]
LCM = yourlist[0]
for i in yourlist[1:]:
    GCF = math.gcd(GCF, i)
LCM = LCM*i//math.gcd(LCM, i)
print(GCF)
print(LCM)

answered May 2, 2019 at 0:05

This would be a good way to find lcm of a list of numbers in Python

from math import gcd
from functools import reduce

def lcm(a,b):
    gc = gcd(a, b) # gcd_of_two_numbers
    lc = (a*b) // gc
    return lc

numbers = [150, 200, 300]
result = reduce(lcm, numbers)
print(result)

answered Nov 3, 2020 at 16:49

How do you find the least common multiple of a list in python?

1

Simple solution to find LCM without using build-in gcd function

def gcd(x,y):
    while y:
         x,y = y,x%y
    return x

for i in ls:
    lcm = (lcm*i) // gcd(lcm,i)

print(lcm)

answered May 22, 2021 at 4:11

How do you find the least common multiple of a list?

How to Find LCM by Listing Multiples.
List the multiples of each number until at least one of the multiples appears on all lists..
Find the smallest number that is on all of the lists..
This number is the LCM..

How do you find the LCM in a for loop in Python?

Step 1:Initially, Get 2 Integer Inputs from the user using int(input()). Step 2:Find the greater number by using an If condition and assign it to the variable 'max'. Step 3:Within the while loop, Use an If condition to check whether the remainder of (max% a) and (max% b) equals to zero or not.

What does LCM mean in Python?

The Least Common Multiple (LCM) is also referred to as the Lowest Common Multiple (LCM) and Least Common Divisor (LCD). For two integers a and b, denoted LCM(a,b), the LCM is the smallest positive integer that is evenly divisible by both a and b.

How do you find HCF and LCM in Python?

Algorithm.
Initialize HCF = 1..
Run a loop in the iteration of (i) between [1, min(num1, num2)].
Note down the highest number that divides both num1 & num2..
If i satisfies (num1 % i == 0 && num2 % i == 0) then new value of HCF is i..
Use lcm formula :- (num1*num2) / hcf..
Print the output..