I’m trying to solve the Smallest Common Multiplier challenge using the code below, but I can’t understand why it’s not working.
If I set count to 60 when I declare it, test will evaluate to true, but when i increment count up from 2 in the while loop it continues past 60 until I get a ‘potential infinite loop’ warning. Why is this?
Any help would be appreciated.
function smallestCommons(arr) {
var range = [];
var count = 2;
var result = 0;
//push to range array
for(var i = arr[0]; i <= arr[1]; i++){
range.push(i);
}
//check if every element in arr is divisible
var test = range.every(function(el) {
return count % el === 0;
});
while(test === false) {
count++;
console.log(count);
}
return count;
}
smallestCommons([1, 5]);
I now have the following - which works (sort of) for the first 4 criteria, but won’t pass the 5th, presumably because counting all the way up to 6056820 is a ridiculously inefficient way of doing this. I’m stuck for other ideas now though.
Edit: actually it did pass. This can’t be a good way to solve this problem though, right?
//
function smallestCommons(arr) {
var highest = Math.max.apply( Math, arr );
var lowest = Math.min.apply( Math, arr );
var range = [];
var count = 2;
var result = 0;
//push to range array
for(var i = lowest; i <= highest; i++){
range.push(i);
}
var modulo = function(el) {
return count % el === 0;
};
//check if every element in arr is divisible
var test = range.every(modulo);
while(test === false) {
count++;
test = range.every(modulo);
if (count > 6056820) {
break;
}
}
return count;
}
smallestCommons([23, 18]);