Least Common Multiple of an array values using Euclidean Algorithm

五迷三道 提交于 2019-12-06 10:41:52

问题


I want to calculate the least common multiple of an array of values, using Euclideans algorithm

I am using this pseudocode implementation: found on wikipedia

function gcd(a, b)
    while b ≠ 0
       t := b; 
       b := a mod b; 
       a := t; 
    return a;

My javascript implementation is such

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

I get error, on my whileloop

Infinite loop

EDIT Some corrections were made, at the end of gcm function, I used 0 as the initial start value, it should be 1, since you can't have a gcm from 0.

EDIT2 The expected output should be 60, since thats the least common multiple of 1,2,3,4,5


回答1:


Did you intentionally tangle all variables and operator sequence? ;-)

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

    //here maxNum = GCD(a,b)

    return (a*b) / (maxNum);  //LCM



回答2:


With ES6

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

const lcm = (a, b) => a * b / gcd(a, b);

Then use reduce on given array of integers:

[1, 2, 3, 4, 5].reduce(lcm); // Returns 60

With ES5

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

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

Then use reduce on given array of integers:

[1, 2, 3, 4, 5].reduce(lcm); // Returns 60


来源:https://stackoverflow.com/questions/47047682/least-common-multiple-of-an-array-values-using-euclidean-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!