Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the LCM of a list of given numbers in Python

Tags:

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.

like image 215
Aradhye Agarwal Avatar asked May 15 '16 11:05

Aradhye Agarwal


People also ask

How do you find the LCM of a list in Python?

Algorithm to find the LCM of array elements gcd() function. At first, find the LCM of initial two numbers using: LCM(a,b) = a*b/GCD(a,b). And, then find the LCM of three numbers with the help of LCM of first two numbers using LCM(ab,c) = lcm(lcm(a1, a2), a3).

How do you find the LCM of n numbers in Python?

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


1 Answers

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

like image 199
Ananay Mital Avatar answered Sep 23 '22 12:09

Ananay Mital