Back

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

I have worked a code to discover the LCM (Lowest Common Multiple) of a rundown of numbers yet there seems, by all accounts, to be a blunder in my code. The code is given beneath: 

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

Benevolently pardon my helpless selection of factors, I demand you to check whether the rationale is right and that the code is useful. 

The syntax error which I am getting is that "factors" is invalid punctuation however I disagree with this. If you don't mind disclose to me where my code isn't right.

1 Answer

0 votes
by (26.4k points)

Try the following code:

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)

I think this helps.

Want to know more details about python? Come and join: Python certification course

Related questions

0 votes
1 answer
asked Apr 27, 2021 in Java by sheela_singh (9.5k points)
0 votes
1 answer

Browse Categories

...