Completely stuck on Smallest Common Multiple

Hi Campers!

I got completely stuck on Smallest Common Multiple challenge.
Can you give my any tips to get started?

Thank you,
Kuba

I think I just don’t understand the algorithm. Translating it later into Javascript shouldn’t be the problem.

Here’s what I created as you suggested - Smallest common multiple for two numbers.
But how to make it working for array of numbers :roll_eyes:

function LCMforTwo(a,b){
var lcm = Math.abs(a * b) / gcd(a,b);
function gcd(a,b){
while (b != 0){
      c = a % b;
      a = b;
      b = c;
    }
 return a;
}
return lcm;
console.log(lcm);
}
LCMforTwo(6541,498);

Hooray! Thank you so much for help :smile:
This is my final code. Gosh, that was really hard.

function smallestCommons(arr){
var min = Math.min(arr[0],arr[1]);
var max = Math.max(arr[0],arr[1]);

var range = [];
for(var i = min; i <= max; i++){
  range.push(i);
}

var lcm = range[0];
for(var j = 1; j < range.length; j++){
  lcm = (lcm * range[j]) / gcd(lcm, range[j]);
}
return lcm;

 function gcd(a,b){
  while (b != 0){
      c = a % b;
      a = b;
      b = c;
    }
 return a;
 }
}
1 Like

I am also stuck, and, before resorting to solving the problem using the solution that has been so generously offered here, I wanted to still share my code here and ask what is wrong (well, even if everything is, I would still like to ask for some help :slight_smile:)

my solution was:
function smallestCommons(arr) {
var newArr = [];
arr.sort(function(a,b){
return a-b
});
for (var i=arr[0]; i<=arr[(arr.length-1)]; i++) {
newArr.push(i);
}
for (var counter=1; counter>newArr[(newArr.length-1)]; counter++){
for (var j=0; j<newArr.length; j++) {
if (counter%arr[j]!==0) break;
}
}
return counter;
}

what I am doing is:

  1. Sorting the initial pair in ascending order.
  2. Creating a new array and pushing the range between the given two number, including the numbers, into the array.
  3. Initializing a counter, potential smallest common multiple, and iterating through the range in my array, trying to see if there is at least ONE number in the range that counter cannot be divided by. If, indeed, counter does not divide evenly by at least one element of the array, I use break statement.
  4. Counter increments, and we are looking again.

I have a feeling when I have an if-break statement I am still doing everything right, but then I just have no idea what to do further. In the meanwhile I will try to use the standard solution with dividing the a*b by the greatest common divisor. Thank you in advance, any help is appreciated!