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.

asked May 15, 2016 at 11:52

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

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

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.

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']

Harsha pps

1,8242 gold badges23 silver badges34 bronze badges

answered Jul 22, 2019 at 17:48

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

Chủ Đề