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

Smallest Common Multiple - Infinite Loop

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
. I then though to encapsulate everything in a while loop that check the number of dividers (if the number of dividers is smaller that the highest number I'm checking for, repeat the process.

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
else {
//clear divisors
divisors = [];
//check next number

return result;


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


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