Tell us what’s happening:
Hello,
my issue is the potential infinite loop creating in my for, and the truth is I am not sure what to put as an end condition for my loop, but the code stops running for the last 2 tests as it doesn’t want to loop indefinitely.
I really think my code could work, although I understand it is neither pretty nor efficient…
Your code so far
function smallestCommons(arr) {
console.log(arr);
arr = arr.sort((a,b)=>a-b);
let a = arr[0];
let b = arr[1];
console.log(a, b, a*b);
let multiplea = 0;
let common = 0;
for (let i = 1; i <= 500000; i++){
multiplea = a * i;
console.log(multiplea);
if (multiplea % b === 0) {
common = multiplea;
console.log("common", common);
for (let j = a; j <= b; j++) {
if (multiplea % j !== 0){
console.log("break", j);
break;
}
if (multiplea % j === 0){
console.log("=", j);
if (j === b) {
console.log(multiplea, j);
return multiplea;
}
}
}
}
}
return arr;
}
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/112.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple
Link to the challenge: