Quick question about my Smallest Common Multiple solution

Is this kind of solution ok? bruteforce coding? My browser wont let me calculate the smallestCommons([23, 18]) without saying is a possible infinite loot, but it works for the Run the tests action.

Your code so far

function smallestCommons(arr) {

/* sorting array from greatest to smallets */
let arrFull=[];
arr.sort((a,b)=> b-a);

/* adding the in between numbers*/
for (let i=arr[0];i>=arr[1];i--) {arrFull.push(i)};

/* variables set up*/
let x=1;
let result =[false];

/* checking if the result array has any false in it and reseting to empty */
while (!result.every(elem=> elem==true)) { result=[];

/* checking every number in the full array to see if pass the if condition, if it is not,adds 1 to the x and try again until the while condition becomes false */
for (let i=0;i<arrFull.length;i++) 
  {if (x % arrFull[i] ==0) 
        else {x++;result.push(false)}}};
return x;



Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36.

Challenge: Smallest Common Multiple

Link to the challenge:

The reason that you are failing with a “possible infinite loop” error is because of how long your code takes to run. The freeCodeCamp process for running tests have a time limit to avoid crashing your browser (as do many other online coding environments). You definitely can refactor your code to be efficient enough not to cause any problems. There’s nothing wrong with looking up the mathematical formulae instead of reinventing them. You’ll still have to implement them in code yourself.

1 Like

This is a case where a little bit of research will go a long way. Lots of people have thought about this problem and it’s great to leverage their math tricks. Your solution works but is inefficient.

If you look here:

The ingredients for a fast solution are:

  1. LCM commutativity: lcm(a, b, c) = lcm(lcm(a, b))
  2. LCM/GCD formula: lcm(a, b) = a*b/gcd(a, b)
  3. Eculid’s algorithm: fast recursive formula for finding GCDs