Hi guys, I managed to solve this algorithm or so I thought but when trying to pass the “smallestCommons([1,13])” it gives me an error. When I ran this code on my machine it returned the right number “360360” but it doesn’t seem to work on this site. Any ideas?
function smallestCommons(arr) {
var allNumbers = [];
var count = 0;
allNumbers.push(arr[0]);
allNumbers.push(arr[1]);
if(arr[1] < arr[0]){
var c = arr[0];
arr[0] = arr[1];
arr[1] = c;
}
for(var i = 0; i < arr[1]; i++){
arr[0]++;
arr[1]--;
allNumbers.push(arr[0]);
allNumbers.push(arr[1]);
if(arr[0] + 1 === arr[1]){
break;
}
}
allNumbers.sort(function(a,b){
return a-b;
});
var firstNum = allNumbers[0];
var multiplier = 1;
for(var i = 0; i < allNumbers.length; i++){
multiplier *= allNumbers[i];
}
for(var i = 0; i < multiplier; i++){
firstNum += allNumbers[0];
for(var j = 1; j < allNumbers.length; j++){
if(firstNum % allNumbers[j] === 0){
count++;
if(count == allNumbers.length - 1){
return firstNum;
}
}
}
count = 0;
}
}
smallestCommons([1,5]);
When I run that specific example (1, 13) in the FCC test window, I get a warning about a potential infinte loop, on (or around) line 36. I personally don’t see an infinite loop, but maybe someone smarter than me can. My guess is that it was just taking too long so the test program panicked.
In any case, you can shut down that check with by putting
// noprotect
as your first line.
I “solved” this algorithm last month and had the same problem as you have. Passes all tests except one. When I run my code in Repl.it it works fine if I choose numbers 19-23 but if I choose 18-23 it crashes with an “infinite loop” warning. I suppose my code works in a manner that adds an nth depth of computation for every additional number (meaning finding the smallest common multiple for all numbers from 18-23 takes perhaps 10 times more computation effort than it does for numbers 19-23?). Just a theory. Not smart enough to figure it out. In any case I made an exception and looked up other solutions which I usually don’t do because to me I felt like my solution was working and I had run out of ideas. Turns out some solutions are pretty simple. Yep this algorithm is tricky.
Thanks. Putting this as a first line worked!
// no protect