Smallest Common Multiple challenge help JavaScript


I’m currently stuck on this challenge:

My code passes the first 5 checks, but fails the last check which according to the console is due to an infinite loop. I think due to the high numbers involved, it thinks the code will go on forever. Is there something that I can add in to my code to prevent this?

function smallestCommons(arr) {
  if (arr[1] < arr[0]) {
    let arrThree = arr[0];
    let arrFour = arr[1];
    arr[0] = arrFour;
    arr[1] = arrThree;
  let x = arr[1] - 1;
  while (x > arr[0]) {
    x -= 1;
  let maxNum = Math.max(...arr);
  let multiple = maxNum;
  for (let i = 0; i < arr.length; i++) {
      if (multiple % arr[i] !== 0) {
        multiple += 1;
        i = 0
  return multiple;


Thanks in advance!

Well that means you need to think about a more efficient algorithm.

The “potential infinite loop” means there is a check in the background for time and resources used. Those are to prevent you from crashing your browser or machine by creating flawed code. You are generally not supposed to prevent that message via arbitrary measures in your code BUT by writing better code.

If you advance and go into coding challenges, you will quickly see that efficient code can make a tremendous difference even on small datasets. And if you think about how that scales up, an efficient algorithm can save you literally dozens of hours.

Please clean your code, you declare a bunch of variables but never use them. I have trouble understanding what your code even does.

Although after copying it and adding a counter to your for-loop… damn that thing runs over 400,000 times!

Please inform yourself on how to use for-loops and while-loops. You are not supposed to change the running-variable within a for-loop.

Also here is a tipp: The smalles common multiple (scm) of two numbers is the product of those two numbers, divided by their largest common denominator (lcd)
scm(a,b) = a*b / lcd(a,b)
Ofcourse you got more numbers, so you need to think about how to adjust for that. But for a start, you need to use multiplication for this challenge.

1 Like

Yeah I think I need to start over. Cheers!

I’d poke around in Wikipedia

1 Like

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