167

你如何计算多个数字的最小公倍数?

到目前为止,我只能在两个数字之间计算它。但不知道如何扩展它以计算 3 个或更多数字。

到目前为止,我就是这样做的

LCM = num1 * num2 /  gcd ( num1 , num2 )

使用 gcd 是计算数字的最大公约数的函数。使用欧几里得算法

但我不知道如何计算 3 个或更多数字。

4

32 回答 32

194

您可以通过迭代计算两个数字的 LCM 来计算两个以上数字的 LCM,即

lcm(a,b,c) = lcm(a,lcm(b,c))
于 2008-09-29T04:37:31.660 回答
150

在 Python 中(修改primes.py):

def gcd(a, b):
    """Return greatest common divisor using Euclid's Algorithm."""
    while b:      
        a, b = b, a % b
    return a

def lcm(a, b):
    """Return lowest common multiple."""
    return a * b // gcd(a, b)

def lcmm(*args):
    """Return lcm of args."""   
    return reduce(lcm, args)

用法:

>>> lcmm(100, 23, 98)
112700
>>> lcmm(*range(1, 20))
232792560

reduce()这样工作:

>>> f = lambda a,b: "f(%s,%s)" % (a,b)
>>> print reduce(f, "abcd")
f(f(f(a,b),c),d)
于 2008-09-29T04:44:40.147 回答
27

这是一个 ECMA 风格的实现:

function gcd(a, b){
    // Euclidean algorithm
    while (b != 0){
        var temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

function lcm(a, b){
    return (a * b / gcd(a, b));
}

function lcmm(args){
    // Recursively iterate through pairs of arguments
    // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))

    if(args.length == 2){
        return lcm(args[0], args[1]);
    } else {
        var arg0 = args[0];
        args.shift();
        return lcm(arg0, lcmm(args));
    }
}
于 2010-04-14T21:48:38.557 回答
17

我会选择这个(C#):

static long LCM(long[] numbers)
{
    return numbers.Aggregate(lcm);
}
static long lcm(long a, long b)
{
    return Math.Abs(a * b) / GCD(a, b);
}
static long GCD(long a, long b)
{
    return b == 0 ? a : GCD(b, a % b);
}

只是一些澄清,因为乍一看它并没有很清楚这段代码在做什么:

Aggregate 是一种 Linq 扩展方法,因此您不能忘记将 using System.Linq 添加到您的引用中。

Aggregate 获得了一个累加函数,因此我们可以在 IEnumerable 上使用属性 lcm(a,b,c) = lcm(a,lcm(b,c))。更多关于聚合

GCD 计算使用欧几里得算法

lcm 计算使用 Abs(a*b)/gcd(a,b) ,参考Reduction by the maximum common divisor

希望这可以帮助,

于 2015-04-18T12:41:34.220 回答
6

我刚刚在 Haskell 中发现了这一点:

lcm' :: Integral a => a -> a -> a
lcm' a b = a`div`(gcd a b) * b
lcm :: Integral a => [a] -> a
lcm (n:ns) = foldr lcm' n ns

我什至花时间写了自己的gcd函数,结果在 Prelude 中找到了!今天学到了很多东西 :D

于 2010-01-26T21:54:06.607 回答
6

一些不需要 gcd 函数的 Python 代码:

from sys import argv 

def lcm(x,y):
    tmp=x
    while (tmp%y)!=0:
        tmp+=x
    return tmp

def lcmm(*args):
    return reduce(lcm,args)

args=map(int,argv[1:])
print lcmm(*args)

这是它在终端中的样子:

$ python lcm.py 10 15 17
510
于 2012-08-07T17:54:27.803 回答
6

这是一个 Python 单线器(不计算导入),用于返回 1 到 20(含)整数的 LCM:

Python 3.5+ 导入:

from functools import reduce
from math import gcd

Python 2.7 导入:

from fractions import gcd

常见逻辑:

lcm = reduce(lambda x,y: x*y // gcd(x, y), range(1, 21))

请注意,在Python 2Python 3中,运算符优先级规则规定*and//运算符具有相同的优先级,因此它们从左到右应用。因此,x*y // z手段(x*y) // z而不是x * (y//z)。两者通常会产生不同的结果。这对于浮点除法没有那么重要,但对于地板除法却很重要。

于 2016-11-02T18:45:47.730 回答
5

这是在Swift中。

// Euclid's algorithm for finding the greatest common divisor
func gcd(_ a: Int, _ b: Int) -> Int {
  let r = a % b
  if r != 0 {
    return gcd(b, r)
  } else {
    return b
  }
}

// Returns the least common multiple of two numbers.
func lcm(_ m: Int, _ n: Int) -> Int {
  return m / gcd(m, n) * n
}

// Returns the least common multiple of multiple numbers.
func lcmm(_ numbers: [Int]) -> Int {
  return numbers.reduce(1) { lcm($0, $1) }
}
于 2018-03-24T16:42:04.050 回答
3

这是 Virgil Disgr4ce 实现的 C# 端口:

public class MathUtils
{
    /// <summary>
    /// Calculates the least common multiple of 2+ numbers.
    /// </summary>
    /// <remarks>
    /// Uses recursion based on lcm(a,b,c) = lcm(a,lcm(b,c)).
    /// Ported from http://stackoverflow.com/a/2641293/420175.
    /// </remarks>
    public static Int64 LCM(IList<Int64> numbers)
    {
        if (numbers.Count < 2)
            throw new ArgumentException("you must pass two or more numbers");
        return LCM(numbers, 0);
    }

    public static Int64 LCM(params Int64[] numbers)
    {
        return LCM((IList<Int64>)numbers);
    }

    private static Int64 LCM(IList<Int64> numbers, int i)
    {
        // Recursively iterate through pairs of arguments
        // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))

        if (i + 2 == numbers.Count)
        {
            return LCM(numbers[i], numbers[i+1]);
        }
        else
        {
            return LCM(numbers[i], LCM(numbers, i+1));
        }
    }

    public static Int64 LCM(Int64 a, Int64 b)
    {
        return (a * b / GCD(a, b));
    }

    /// <summary>
    /// Finds the greatest common denominator for 2 numbers.
    /// </summary>
    /// <remarks>
    /// Also from http://stackoverflow.com/a/2641293/420175.
    /// </remarks>
    public static Int64 GCD(Int64 a, Int64 b)
    {
        // Euclidean algorithm
        Int64 t;
        while (b != 0)
        {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }
}'
于 2012-12-05T20:26:29.997 回答
3

以及 Scala 版本:

def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
def gcd(nums: Iterable[Int]): Int = nums.reduce(gcd)
def lcm(a: Int, b: Int): Int = if (a == 0 || b == 0) 0 else a * b / gcd(a, b)
def lcm(nums: Iterable[Int]): Int = nums.reduce(lcm)
于 2016-11-14T19:09:59.413 回答
3

查找任何数字列表的 lcm 的函数:

 def function(l):
     s = 1
     for i in l:
        s = lcm(i, s)
     return s
于 2016-11-20T12:52:42.830 回答
2

使用 LINQ,您可以编写:

static int LCM(int[] numbers)
{
    return numbers.Aggregate(LCM);
}

static int LCM(int a, int b)
{
    return a * b / GCD(a, b);
}

应该添加using System.Linq;并且不要忘记处理异常......

于 2014-04-24T12:27:31.957 回答
1

你可以用另一种方式来做 - 让有 n 个数字。取一对连续的数字并将其 lcm 保存在另一个数组中。在第一次迭代程序中执行此操作会进行 n/2 次迭代。然后接下来从 0 开始拾取对,例如 (0,1) , (2,3) 等等。计算它们的 LCM 并存储在另一个数组中。这样做直到你只剩下一个数组。(如果 n 为奇数,则无法找到 lcm)

于 2011-09-14T06:56:56.057 回答
1

ES6 风格

function gcd(...numbers) {
  return numbers.reduce((a, b) => b === 0 ? a : gcd(b, a % b));
}

function lcm(...numbers) {
  return numbers.reduce((a, b) => Math.abs(a * b) / gcd(a, b));
}
于 2013-06-16T19:13:54.793 回答
1

在 R 中,我们可以使用包numbers中的函数mGCD (x) 和mLCM (x)来计算整数向量 x 中所有数字的最大公约数和最小公倍数:

    library(numbers)
    mGCD(c(4, 8, 12, 16, 20))
[1] 4
    mLCM(c(8,9,21))
[1] 504
    # Sequences
    mLCM(1:20)
[1] 232792560
于 2015-04-05T15:15:35.113 回答
1

只是为了好玩,一个外壳(几乎所有外壳)实现:

#!/bin/sh
gcd() {   # Calculate $1 % $2 until $2 becomes zero.
      until [ "$2" -eq 0 ]; do set -- "$2" "$(($1%$2))"; done
      echo "$1"
      }

lcm() {   echo "$(( $1 / $(gcd "$1" "$2") * $2 ))";   }

while [ $# -gt 1 ]; do
    t="$(lcm "$1" "$2")"
    shift 2
    set -- "$t" "$@"
done
echo "$1"

试试看:

$ ./script 2 3 4 5 6

要得到

60

最大的输入和结果应该小于(2^63)-1或 shell 数学将换行。

于 2016-11-25T00:56:21.307 回答
1

我正在寻找数组元素的 gcd 和 lcm 并在以下链接中找到了一个很好的解决方案。

https://www.hackerrank.com/challenges/between-two-sets/forum

其中包括以下代码。gcd 的算法使用的欧几里得算法在下面的链接中得到了很好的解释。

https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm

private static int gcd(int a, int b) {
    while (b > 0) {
        int temp = b;
        b = a % b; // % is remainder
        a = temp;
    }
    return a;
}

private static int gcd(int[] input) {
    int result = input[0];
    for (int i = 1; i < input.length; i++) {
        result = gcd(result, input[i]);
    }
    return result;
}

private static int lcm(int a, int b) {
    return a * (b / gcd(a, b));
}

private static int lcm(int[] input) {
    int result = input[0];
    for (int i = 1; i < input.length; i++) {
        result = lcm(result, input[i]);
    }
    return result;
}
于 2016-12-26T13:21:22.203 回答
1

这是PHP的实现:

    // https://stackoverflow.com/q/12412782/1066234
    function math_gcd($a,$b) 
    {
        $a = abs($a); 
        $b = abs($b);
        if($a < $b) 
        {
            list($b,$a) = array($a,$b); 
        }
        if($b == 0) 
        {
            return $a;      
        }
        $r = $a % $b;
        while($r > 0) 
        {
            $a = $b;
            $b = $r;
            $r = $a % $b;
        }
        return $b;
    }

    function math_lcm($a, $b)
    {
        return ($a * $b / math_gcd($a, $b));
    }

    // https://stackoverflow.com/a/2641293/1066234
    function math_lcmm($args)
    {
        // Recursively iterate through pairs of arguments
        // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))

        if(count($args) == 2)
        {
            return math_lcm($args[0], $args[1]);
        }
        else 
        {
            $arg0 = $args[0];
            array_shift($args);
            return math_lcm($arg0, math_lcmm($args));
        }
    }

    // fraction bonus
    function math_fraction_simplify($num, $den) 
    {
        $g = math_gcd($num, $den);
        return array($num/$g, $den/$g);
    }


    var_dump( math_lcmm( array(4, 7) ) ); // 28
    var_dump( math_lcmm( array(5, 25) ) ); // 25
    var_dump( math_lcmm( array(3, 4, 12, 36) ) ); // 36
    var_dump( math_lcmm( array(3, 4, 7, 12, 36) ) ); // 252

归功于@T3db0t上面的回答(ECMA 风格的代码)

于 2017-09-27T10:14:53.820 回答
0

GCD 需要对负数进行一些修正:

def gcd(x,y):
  while y:
    if y<0:
      x,y=-x,-y
    x,y=y,x % y
    return x

def gcdl(*list):
  return reduce(gcd, *list)

def lcm(x,y):
  return x*y / gcd(x,y)

def lcml(*list):
  return reduce(lcm, *list)
于 2013-01-04T18:03:08.470 回答
0

这个怎么样?

from operator import mul as MULTIPLY

def factors(n):
    f = {} # a dict is necessary to create 'factor : exponent' pairs 
    divisor = 2
    while n > 1:
        while (divisor <= n):
            if n % divisor == 0:
                n /= divisor
                f[divisor] = f.get(divisor, 0) + 1
            else:
                divisor += 1
    return f


def mcm(numbers):
    #numbers is a list of numbers so not restricted to two items
    high_factors = {}
    for n in numbers:
        fn = factors(n)
        for (key, value) in fn.iteritems():
            if high_factors.get(key, 0) < value: # if fact not in dict or < val
                high_factors[key] = value
    return reduce (MULTIPLY, ((k ** v) for k, v in high_factors.items()))
于 2013-05-30T02:53:00.890 回答
0
clc;

data = [1 2 3 4 5]

LCM=1;

for i=1:1:length(data)

    LCM = lcm(LCM,data(i))

end 
于 2014-04-25T03:09:29.890 回答
0

我们在微积分上实现了最小公倍数,它适用于任意数量的输入,也显示步骤。

我们所做的是:

0: Assume we got inputs[] array, filled with integers. So, for example:
   inputsArray = [6, 15, 25, ...]
   lcm = 1

1: Find minimal prime factor for each input.
   Minimal means for 6 it's 2, for 25 it's 5, for 34 it's 17
   minFactorsArray = []

2: Find lowest from minFactors:
   minFactor = MIN(minFactorsArray)

3: lcm *= minFactor

4: Iterate minFactorsArray and if the factor for given input equals minFactor, then divide the input by it:
  for (inIdx in minFactorsArray)
    if minFactorsArray[inIdx] == minFactor
      inputsArray[inIdx] \= minFactor

5: repeat steps 1-4 until there is nothing to factorize anymore. 
   So, until inputsArray contains only 1-s.

就是这样 - 你得到了你的 lcm。

于 2015-02-05T16:26:47.500 回答
0

LCM 既是关联的又是可交换的。

LCM(a,b,c)=LCM(LCM(a,b),c)=LCM(a,LCM(b,c))

这是C中的示例代码:

int main()
{
  int a[20],i,n,result=1;  // assumption: count can't exceed 20
  printf("Enter number of numbers to calculate LCM(less than 20):");
  scanf("%d",&n);
  printf("Enter %d  numbers to calculate their LCM :",n);
  for(i=0;i<n;i++)
    scanf("%d",&a[i]);
 for(i=0;i<n;i++)
   result=lcm(result,a[i]);
 printf("LCM of given numbers = %d\n",result);
 return 0;
}

int lcm(int a,int b)
{
  int gcd=gcd_two_numbers(a,b);
  return (a*b)/gcd;
}

int gcd_two_numbers(int a,int b)
{
   int temp;
   if(a>b)
   {
     temp=a;
     a=b;
     b=temp;
   }
  if(b%a==0)
    return a;
  else
    return gcd_two_numbers(b%a,a);
}
于 2015-02-23T05:16:26.777 回答
0

方法 compLCM 接受一个向量并返回 LCM。所有数字都在向量 in_numbers 内。

int mathOps::compLCM(std::vector<int> &in_numbers)
 {
    int tmpNumbers = in_numbers.size();
    int tmpMax = *max_element(in_numbers.begin(), in_numbers.end());
    bool tmpNotDividable = false;

    while (true)
    {
        for (int i = 0; i < tmpNumbers && tmpNotDividable == false; i++)
        {
            if (tmpMax % in_numbers[i] != 0 )
                tmpNotDividable = true;
        }

        if (tmpNotDividable == false)
            return tmpMax;
        else
            tmpMax++;
    }
}
于 2015-04-30T21:05:04.370 回答
0

对于任何寻找快速工作代码的人,试试这个:

我编写了一个函数lcm_n(args, num) ,它计算并返回数组中所有数字的 lcm args。第二个参数num是数组中数字的计数。

将所有这些数字放入一个数组中args,然后调用函数lcm_n(args,num);

此函数返回所有这些数字的 lcm。

下面是函数的实现lcm_n(args, num)

int lcm_n(int args[], int num) //lcm of more than 2 numbers
{
    int i, temp[num-1];

    if(num==2)
    {
        return lcm(args[0], args[1]);
    }
    else
    {
        for(i=0;i<num-1;i++)
        {
           temp[i] = args[i];   
        }

        temp[num-2] = lcm(args[num-2], args[num-1]);
        return lcm_n(temp,num-1);
    }
}

此功能需要以下两个功能才能工作。因此,只需将它们与它一起添加即可。

int lcm(int a, int b) //lcm of 2 numbers
{
    return (a*b)/gcd(a,b);
}


int gcd(int a, int b) //gcd of 2 numbers
{
    int numerator, denominator, remainder;

    //Euclid's algorithm for computing GCD of two numbers
    if(a > b)
    {
        numerator = a;
        denominator = b;
    }
    else
    {
        numerator = b;
        denominator = a;
    }
    remainder = numerator % denominator;

    while(remainder != 0)
    {
        numerator   = denominator;
        denominator = remainder;
        remainder   = numerator % denominator;
    }

    return denominator;
}
于 2016-01-07T17:55:18.987 回答
0

int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a%b); } int lcm(int[] a, int n) { int res = 1, i; for (i = 0; i < n; i++) { res = res*a[i]/gcd(res, a[i]); } return res; }

于 2016-09-15T15:51:35.383 回答
0

在蟒蛇中:

def lcm(*args):
    """Calculates lcm of args"""
    biggest = max(args) #find the largest of numbers
    rest = [n for n in args if n != biggest] #the list of the numbers without the largest
    factor = 1 #to multiply with the biggest as long as the result is not divisble by all of the numbers in the rest
    while True:
        #check if biggest is divisble by all in the rest:
        ans = False in [(biggest * factor) % n == 0 for n in rest]
        #if so the clm is found break the loop and return it, otherwise increment factor by 1 and try again
        if not ans:
            break
        factor += 1
    biggest *= factor
    return "lcm of {0} is {1}".format(args, biggest)

>>> lcm(100,23,98)
'lcm of (100, 23, 98) is 112700'
>>> lcm(*range(1, 20))
'lcm of (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19) is 232792560'
于 2016-12-25T13:50:42.020 回答
0

这是我用的——

def greater(n):

      a=num[0]

      for i in range(0,len(n),1):
       if(a<n[i]):
        a=n[i]
      return a

r=input('enter limit')

num=[]

for x in range (0,r,1):

    a=input('enter number ')
    num.append(a)
a= greater(num)

i=0

while True:

    while (a%num[i]==0):
        i=i+1
        if(i==len(num)):
               break
    if i==len(num):
        print 'L.C.M = ',a
        break
    else:
        a=a+1
        i=0
于 2017-02-16T20:40:35.470 回答
0

对于蟒蛇 3:

from functools import reduce

gcd = lambda a,b: a if b==0 else gcd(b, a%b)
def lcm(lst):        
    return reduce(lambda x,y: x*y//gcd(x, y), lst)  
于 2018-08-22T02:09:50.597 回答
0

在 Ruby 中,它很简单:

> [2, 3, 4, 6].reduce(:lcm)
=> 12

> [16, 32, 96].reduce(:gcd)
=> 16

(在 Ruby 2.2.10 和 2.6.3 上测试。)

于 2020-05-21T10:13:28.920 回答
0

Python 3.9math模块gcdlcm对数字列表的支持。

import math

lst = [1,2,3,4,5,6,7,8,9]

print(math.lcm(*lst))

print(math.gcd(*lst))
于 2020-10-15T11:30:24.070 回答
-2

如果没有时间限制,这相当简单直接:

def lcm(a,b,c):
    for i in range(max(a,b,c), (a*b*c)+1, max(a,b,c)):
        if i%a == 0 and i%b == 0 and i%c == 0:
            return i
于 2018-06-27T19:53:09.960 回答