Miha Šušteršič - 2 months ago 23

Javascript Question

I'm working on a freeCodeCamp exercise called Smallest Common Multiplier. The purpose of the exercise is the following:

Find the smallest common multiple of the provided parameters that can

be evenly divided by both, as well as by all sequential numbers in the

range between these parameters.

The range will be an array of two numbers that will not necessarily be

in numerical order.

e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3

that is evenly divisible by all numbers between 1 and 3.

I thought I could save this by sorting the elements in the array passed to the function from smallest to largest, then check with a for loop for all the numbers whether or not

`number % x === 0`

It seems that I've written an infinite loop that crashes my browser.

`function smallestCommons(arr) {`

//sort from smallest to largest

arr.sort(function(a, b) {

return a-b;

});

var result = 1;

var divisors = [];

//while number of divisors !== last number to check

while(divisors.length < arr[1]) {

//check if number divides result

for(var x = arr[0]; x < arr[1]; x++) {

//if it divides result

if(result % x === 0) {

//push it to divisors

divisors.push(x);

}

else {

//clear divisors

divisors = [];

}

}

//check next number

result++;

}

return result;

}

smallestCommons([5,1]);

Can you point out what I'm doing wrong, and maybe point out how to approach the exercise?

Answer

Notice that you clean `divisors`

array in the else part of your function.
That way you can't pass the condition `divisors.length >= arr[1]`

However your implementation of LCM is not working at all