Intermediate Algorithm Scripting - Smallest Common Multiple

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:

Inefficiency can activate the infinite loop protection.

You can decrease the inefficiency enough to pass by fixing two issues:

Every multiple of b goes through numbers faster than every multiple of a

console.log statements are very slow.

I’d definitely look at the solutions once you fix those issues - your code works but the logic is a bit more complex that you strictly need, which is also slowing your code down a bit.

Thanks!! It’s gone through. I print everything to be able to follow where the code is at and what it is doing, forgot it is unnecessary steps.
I don’t quite understand all of the solution, especially the upperBound step.

You can print while writing the code, sure, but you need to remove or comment out those console.log statements or your code will get really, really slowed down by them.

If you have questions about the solutions, go ahead and copy them over here and ask about specific parts.

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