Smallest Common Multiple

Hello everyone,

I’ve managed to write something that half works but seems to be failing when it comes to handling larger numbers. I also get the infinite loop warning that I guess is also referring to the numbers being too big. I’m aware that what I’ve written probably isn’t the most efficient way to solve the problem, but I’d like to try and understand why it’s failing before I try something else! Any help or advice is hugely appreciated. Thankyou!


function smallestCommons(arr) {
  let sortedArr = arr.sort((a,b) => a - b);
  let rangeArr = [];
  let rangeProduct = 1;
  let commonMultiples = [];

  for (let i = sortedArr[0]; i <= sortedArr[1]; i++) {
    rangeArr.push(i);
    rangeProduct *= i;
  };

  for (let j = rangeProduct; j > 0; j--) {
    let possibleMultiple = true;

    for (let k = rangeArr.length - 1; k >= 0; k--) {
      possibleMultiple === true && j % rangeArr[k] === 0
        ? possibleMultiple = true
        : possibleMultiple = false;
    }
    if (possibleMultiple === true) {
      commonMultiples.unshift(j);
    };
  };
  return commonMultiples[0];
};

smallestCommons([5, 1]);

I’ve rewritten it slightly, testing an Array of the possible products rather than all numbers less than a product and all the tests pass except the last. This makes me think the theory is sound , but again it’s struggling with large numbers. Or I’m completely wrong!


function smallestCommons(arr) {
  let sortedArr = arr.sort((a,b) => a - b);
  let rangeArr = [];
  let rangeProductArr = [];
  let maxRangeProduct = 1;

  for (let i = sortedArr[0]; i <= sortedArr[1]; i++) {
    rangeArr.push(i);
    maxRangeProduct *= i;
  };

  let commonMultiples = [maxRangeProduct];  

  for (let j = 0; j < rangeArr.length; j++) {
    for (let k = 0; k < rangeArr.length; k++) {
      if (j != k 
      && rangeProductArr.indexOf(rangeArr[j] * rangeArr[k]) === -1) 
      {
        rangeProductArr.push(rangeArr[j] * rangeArr[k]);
      }
      for (let l = 0; l < rangeProductArr.length; l++) {
        if (rangeProductArr[l] % rangeArr[k] > 0 
        && rangeProductArr.indexOf(rangeProductArr[l] * rangeArr[k]) === -1)
        {
          rangeProductArr.push(rangeProductArr[l] * rangeArr[k]);
        }
      }
    }
  }

  for (let m = 0; m < rangeProductArr.length; m++) {
    let possibleMultiple = true;

    for (let n = 0; n < rangeArr.length; n++) {
      possibleMultiple === true && rangeProductArr[m] % rangeArr[n] === 0
        ? possibleMultiple = true
        : possibleMultiple = false;
    }
    if (possibleMultiple === true 
      && rangeProductArr[m] < commonMultiples[0]) 
      {
      commonMultiples.unshift(rangeProductArr[m]);
      };
    };
  return commonMultiples[0];
};

smallestCommons([2, 10]);

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