Smallest Common Multiple | Can't pass last test but works on node

Smallest Common Multiple | Can't pass last test but works on node
0

#1

Tell us what’s happening:

Your code so far


function smallestCommons(arr) {
  function checkLCM() {
    for(let item of arr) {
      if(lcm % item !== 0) {
        return true
      } 
    }
    return false
  }

  arr.sort((a, b) => a - b) 

  const max = arr.pop()
  for(let i = arr[0] + 1; i < max; i++) {
    arr.push(i)
  }

  let multiplier = 1;
  let seekingLCM = true
  let lcm = max * multiplier

  while(seekingLCM) {
    lcm = max * multiplier;

    seekingLCM = checkLCM()
    multiplier++
  }

  return lcm
}


smallestCommons([23, 18]); // 1945225;  number changes, which shows that it is being stopped

Hello guys! My code above is not passing the last test which is smallestCommons([23, 18]) should return 6056820. and I’m sure it’s because it takes too long so freecodecamp stops it. It works on node and even on the browser console. I used // noprotect at the top the code and still failed. I already passed the whole challenge by making use of the every method(last code box below) . Then I wanted to use a procedural solution instead of using every, so I used an inner function called checkLCM(). The code box directly below is comparing where I all I did was replace the every with calling the checkLCM() function inside the while loop. The code that does pass is the last code box.


//passing solution
while(seekingLCM) {
  lcm = max * multiplier;

  seekingLCM = !arr.every(item => lcm % item === 0)
  multiplier++
}

//non-passing solution
while(seekingLCM) {
  lcm = max * multiplier;

  seekingLCM = checkLCM()
  multiplier++
}
function smallestCommons(arr) {
  arr.sort((a, b) => a - b) 

  const max = arr.pop()
  for(let i = arr[0] + 1; i < max; i++) {
    arr.push(i)
  }

  let multiplier = 1;
  let seekingLCM = true
  let lcm = max * multiplier

  while(seekingLCM) {
    lcm = max * multiplier;

    seekingLCM = !arr.every(item => lcm % item === 0)
    multiplier++
  }

  return lcm
}


smallestCommons([23, 18]); // 6056820 way it works!

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple/


#2

You’re right, it’s taking too long, though I can’t see why

I wonder if you time it whether or not the passing solution only barely passes, and it’s the overhead of the function calls that’s doing it

If you want a hint that should speed things up for definite note that the LCM of three numbers is LCM(LCM(a, b), c) which looks suspiciously like a higher order function you might have heard of…

Also there’s a pretty great way of finding it based on the GCD which has a very famous and old algorithm which is pretty quick