# Smallest Common Multiple - Infinite loop problems

Smallest Common Multiple - Infinite loop problems
0

#1

Been at this challenge for days. I’ve tried several different methods but I seem to keep running into a infinite loop. Can anyone spot the error? Line 20 just after while(k)

function smallestCommons(arr)
{

var newArr = [];

arr.sort(function(low, high)
{
return high - low;

});
for (var i = arr[0]; i >= arr[1]; i--)
{
newArr.push(i);
}
var k = true;
var mult = 1;

while(k)
{
mult++;
for (var j = newArr[0]; j <= newArr[newArr.length - 1]; j++)
{
if (mult % j !== 0)
{
break;
}
else if ( j == newArr[newArr.length - 1])
{
k = false;
}
}
}
return mult;
}
smallestCommons([1,13]);

#2

In the test case of smallestCommons([1, 13]), before entering the while loop, newArr references the following array: [ 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ].

Before the for loop begins, newArray[0] = 13, so the for loop never executes anything inside it, because j = 13 and newArr[newArr.length - 1] = 1. Since k never gets assigned the value false, the while loop keeps looping.

#3

for (var j = newArr[0]; j <= newArr[newArr.length - 1]; j++)

I’m lost , how can I increment from newArr[0] to newArr[1] etc. to the end of the array? Or, should I not reverse the array?

#4

It seems you’re trying to loop over the elements of newArr, however what you’ve written doesn’t actually do this.

You’re probably looking for for (var j in newArr) to set j to the actual elements of newArr.

Try writing down what happens to the value of j in your current loop attempt at each iteration, and you’ll see what @RandellDawson meant with their comment.

Good luck, and happy coding!

#5

I rewrote my code and now I pass all but the last test. I still get the infinite loop warning when trying to run the last test???

var newArr = arr.sort();
var arr2 = [];

for (var i = newArr[0]; i <= newArr[newArr.length - 1]; i++)
{
arr2.push(i);
}

var k = true;
var total = 0;

while (k)
{
total++;

for (var j = arr2[0]; j <= arr2[arr2.length - 1]; j++)
{
if (total % j !== 0)
{
break;
}
else if (j == arr2[arr2.length - 1])
{
k = false;
}
}
}