Intermediate Algorithm Scripting - Smallest Common Multiple

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) {
    } if (found==true){
    else if(found==false){

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/ Safari/537.36

Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple

Link to the challenge:

How can this be when you don’t have a return statement in your code?

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

Why i > 1? I don’t think that’s correct

1 Like

I was just in the middle of typing the same thing :slight_smile:

@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?

1 Like

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)

Ive typed out my logic replying to another comment. Do lmk if it makes sense.

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?

oh yeah, my bad that makes sense. It just has to go down to the smaller value inputted. So I changed the loop to

for (let i = num - 1; i >= arr[0]; i--)

But the same error of greater than 17 persists.

Interesting. I copied your original code and made the following changes:

  • Changed the console.log to a return
  • Fixed the for loop as you noted above

And all tests passed for me.

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?

The GCD and LCM algorithm is the fastest approach I know.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.