Hi, my code works for any two inputted numbers as long as they are less than 17. Once one of the numbers is 17 or greater, the code breaks citing a possible infinite loop. Not sure how there can be an infinite loop in one case but it works in another. Where am i going wrong
Your code so far
function smallestCommons(arr) {
let answer = true
arr.sort(function (a, b) {
return a - b;
});
let multiplier=1
let new_num=arr[1]
while (answer) {
let found=true
let num = arr[1]
for (let i = num - 1; i > 1; i--) {
if (new_num % i != 0) {
found=false
}
} if (found==true){
answer=false
console.log(new_num)
}
else if(found==false){
multiplier++
new_num=num*multiplier
}
}
}
smallestCommons([1, 17]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple
My bad, it was originally return new_num. I had changed it to console to see what was getting printed and forgot the change it back before posting. The issue persists with the return keyword as well
@drunk_penguin Don’t you just need to check the range of numbers passed into the function. Why would you need to check all the way down to 2 every time?
So the logic I was trying to apply was, say the input is [1,5]. So I take the largest number which is five here, and check if it is divisible by 4,3,2 (not checking for 1 since every number is divisble by 1). If that fails, next check if 10 is divisible by 4,3,2. Then check if 15 is divisible by 4,3,2 etc. Does this make sense? (5,10,15 and the other multiples are always gonna be divisible by 5)
Your logic is fine. But the range passed into the function doesn’t always start with 1. For example, the last test range is [18, 23]. So I’ll ask again, does your for loop always need to go all the way down to 2?
My bad, I realised I put just i> instead of >=. It works for me too thanks for your help!
Also on a side note, is there any way to make the code more efficient?