learningjavascriptks
learningjavascriptks

Reputation: 325

How to Calculate LCM in an array or Multiple integers with Euclid Algorithm?

I have this assignment of euclid algorithm, my solution is based on wiki hows' solution, I got this code which calculates LCM of 2 numbers only correctly. I already tried other methods on wiki hows' but my logic is very wrong.

How can I apply this code to a range of numbers? base on this code like [245,244,243...45]. I have to get LCM of multiple numbers

function smallestCommons(arr) {
var max,
  min,
  product,
  rem;

max = Math.max.apply(Math, arr);
min = Math.min.apply(Math, arr);

  product = max*min;

 function gcd(max,min) {
 debugger;
 rem = max%min;
 max=min; // update variables until remainder is equal to 0
 min=rem;
 if(rem === 0) {
 return max; // return the max variable for GCD
  } else {
 return  gcd(max,min);
 }
 }

 return  product / gcd(max,min);
}

smallestCommons([210,45]);

Upvotes: 2

Views: 782

Answers (1)

kandhan
kandhan

Reputation: 523

To get LCM of multiple numbers, do recursion. If you have three numbers 2,3,4; then take lcm of 3 and 4 and then take lcm of 2 with that. Like:

lcm(2,lcm(3,4))

Code:

//This is your function
function gcd(max,min){
    rem = max%min;
    max=min; // update variables until remainder is equal to 0
    min=rem;
    if(rem === 0) {
        return max; // return the max variable for GCD
    } 
    else {
        return  gcd(max,min);
    }
}

//This function computes the LCM
function lcm(a,b){
    return (a*b)/gcd(a,b)
}

//This function is the Iterator, it computes the LCM for the numbers
//in the INPUT array recursively by calling the previous function
function lcmIter(arr,len){
    //LENGTH of array -> 2 is the base case here, if there are only  
    //two numbers just compute its LCM and return it.
    if(len === 2){
        return lcm(arr[0],arr[1])
    }
    //If there are more than two numbers, compute the LCM of last 
    //number with the rest of array(now the array is one less)
    else{
        return lcm(arr[len-1],lcmIter(arr,len-1))
    }
}
//This is your input array
var array = [2,3,4,5]
//call your iterator with the array and its length
console.log(lcmIter(array,array.length))

Upvotes: 1

Related Questions