Tell us what’s happening:
Hey there kind people,
I think I have made a working snippet of code.
However, the infinite loop checker just stops the code before it finishes.
I don’t know how to make it repeat until just that, so I used an always-true loop and have it break off later. Can I bypass the infinite loop protection?
Your code so far
function smallestCommons(arr) {
let numbersInBetween = [];
let solution = Math.max(...arr);
let counter = 0;
if(arr[1] > arr[0]) {
for(let i = arr[0]; i <= arr[1]; i++) {
numbersInBetween.push(i);
}
} else {
for(let i = arr[1]; i <= arr[0]; i++) {
numbersInBetween.push(i);
}
}
console.log(numbersInBetween);
for(let j = 0; j < Infinity; j++) {
for(let i = 0; i < numbersInBetween.length; i++) {
if(solution * j % numbersInBetween[i] === 0) {
counter = counter + 1;
}
if (counter == numbersInBetween.length) {
break;
}
}
}
console.log(solution);
}
smallestCommons([1,5]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36.
Refactor is a term that means generating the same output but improving how the code reaches this solution. For example, in your code, you can 1) establish a maximum bound and 2) increment by a better value than 1 in your j loop.
Though, in order to get truly efficient code, I’d recommend avoiding loops and researching how to do this efficiently with GCD and LCM.
I still ended up using loops, but I fixed the issue. I was never good at writing short code.
function smallestCommons(arr) {
let numbersInBetween = [];
let solution = Math.max(...arr); // maximum of array to multiply and efficiency
let multipleFound = false; // no multiple before checking
if(arr[1] > arr[0]) {//checking if the largest array number is first or second
for(let i = arr[0]; i <= arr[1]; i++) {
numbersInBetween.push(i);
}
} else {
for(let i = arr[1]; i <= arr[0]; i++) {
numbersInBetween.push(i);
}
}
console.log(numbersInBetween);
while(multipleFound == false) { // find smallest common multiple
let counter = 0; //counter is used to count how many divisors
solution = solution + Math.max(...arr);
for( let i = 0; i < numbersInBetween.length; i++) {
if(solution % numbersInBetween[i] == 0) {
counter = counter + 1; // see how many are divisible
}
}
if (counter == numbersInBetween.length) {
multipleFound = true; // get out of the loop when multiple is found
}
}
return(solution);
}
smallestCommons([1,5]);
Those are some good improvements. I’m not a big fan of short code, but luckily fast code doesn’t have to be short. In this case though, I think you’ve got it close to as fast as you can with loops.