使用欧几里德算法的最小公倍数值

Vin*_*ang 2 javascript algorithm lcm greatest-common-divisor

我想使用欧几里得算法计算值数组的最小公倍数

我正在使用这个伪代码实现:在维基百科上找到

function gcd(a, b)
    while b ? 0
       t := b; 
       b := a mod b; 
       a := t; 
    return a;
Run Code Online (Sandbox Code Playgroud)

我的javascript实现就是这样

function smallestCommons(arr) {

  var gcm = arr.reduce(function(a,b){

    let minNum = Math.min(a,b);
    let maxNum = Math.max(a,b);
    var placeHolder = 0;

    while(minNum!==0){
        placeHolder = maxNum;
        maxNum = minNum;
        minNum = placeHolder%minNum;
    } 

    return (a*b)/(minNum);
  },1);

  return gcm;
}


smallestCommons([1,2,3,4,5]);
Run Code Online (Sandbox Code Playgroud)

在我的whileloop上我得到错误

无限循环

编辑进行了一些修正,在gcm函数结束时,我使用0作为初始起始值,它应该是1,因为你不能从0开始有一个gcm.

EDIT2预期输出应为60,因为这是1,2,3,4,5的最小公倍数

Ели*_* Й. 11

使用ES6

const gcd = (a, b) => a ? gcd(b % a, a) : b;

const lcm = (a, b) => a * b / gcd(a, b);
Run Code Online (Sandbox Code Playgroud)

然后在给定的整数数组上使用reduce:

[1, 2, 3, 4, 5].reduce(lcm); // Returns 60
Run Code Online (Sandbox Code Playgroud)

使用ES5

var gcd = function (a, b) {
    return a ? gcd(b % a, a) : b;
}

var lcm = function (a, b) {
    return a * b / gcd(a, b);
}
Run Code Online (Sandbox Code Playgroud)

然后在给定的整数数组上使用reduce:

[1, 2, 3, 4, 5].reduce(lcm); // Returns 60
Run Code Online (Sandbox Code Playgroud)

  • 之所以美丽,是因为它短而精巧。最佳答案IMO。 (2认同)