在 Python 中计算给定数字列表的 LCM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37237954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:06:39  来源:igfitidea点击:

Calculate the LCM of a list of given numbers in Python

python

提问by Aradhye Agarwal

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:

我编写了一个代码来找出数字列表的 LCM(最低公倍数),但我的代码中似乎有错误。代码如下:

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 syntaxthough I don't agree with this. Please tell me where my code is wrong.

我得到的语法错误是“因素”是无效的语法,尽管我不同意这一点。请告诉我我的代码哪里错了。

回答by Ananay Mital

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 = a[0]
for i in a[1:]:
  lcm = lcm*i/gcd(lcm, i)
print lcm

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

希望这可以帮助。欢迎所有查询,贡献和评论:)

回答by TakingItCasual

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

回答by Jay Patel

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)

回答by Matt Pitkin

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

在 Numpy v1.17(在撰写本文时,非发布开发版本)中有一个lcm函数可以用于两个数字,例如:

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 gcdfunction.

还有一个gcd功能。

回答by Vinodh Velumayil

To find LCM of given list of numbers

查找给定数字列表的 LCM

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)

回答by Jay Patel

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

您在第三行中缺少一个右括号 (')')。因此,线因素的误差。

Moreover in last second line of your first function, you've named the variable

此外,在您的第一个函数的最后第二行中,您已将变量命名为

factors as factor

change that too.

也改变一下。

回答by Yashwanth

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

不使用任何数学函数的更快方法是计算 GCD 和计算 LCM。

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

Now find LCM using GCF

现在使用 GCF 找到 LCM

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)

回答by harshavardhan joshi

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<c):
 for p in range(len(a)):

   if(j%int(a[p])==0):
       count=count+1

       if(count==len(a)):
           print('in count counter',count)    
           print('in count',j)        
           flag=1
           break
       else:

           flag=0
   else:
       break
 if(flag==1):
      print('flag',j)        
      break
 else:
           count=0
           j=j+1    

print(j)enter code here
print("count",count)

回答by ssp4all

Find LCM and GCD of a list of numbers

查找数字列表的 LCM 和 GCD

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

阅读所有这些解决方案后,仍然不清楚,这是我可能的最简单方法:)

find LCM using GCD

使用 GCD 查找 LCM

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

回答by Mathieu CAROFF

mathcontains a gcdfunction. The lowest common multiple of the several number is the iterated lowest common multiple so we can use functools.reduce. Note I'm passing 1as third argument to reduce. This allows llcm to handle the trivial case of abeing empty.

math包含一个gcd函数。几个数的最小公倍数是迭代的最小公倍数,因此我们可以使用functools.reduce. 注意我1作为第三个参数传递给reduce。这允许 llcm 处理a空的微不足道的情况。

def lcm(a, b):
    "Lowest common multiple"
    import math as m
    return a * b // m.gcd(a, b)

def ilcm(a):
    "Iterated lowest common multiple"
    import functools as f
    return f.reduce(lcm, a, 1)

assert ilcm([]) == 1
assert ilcm([0]) == 0
assert ilcm([2, 3, 4, 5]) == 60
assert ilcm([0, 2, 3, 4, 5]) == 0