Smallest Common multiple - doesn't pass all tests

Hello community,

Need help understanding this assignment I’ve spent so much time on this. I don’t know why I’m not getting it. It’s discouraging. Although I looked at the answers on the FreeCodeCamp, I still don’t seem to get it right. It says I can run on an infinite loop when passing the last test. Any help is much appreciated!


function smallestCommons(arr) {
 let sortNums = arr.sort((a,b)=> a-b);
 let smallNum = sortNums[0];
 let bigNum = sortNums[1];
 //let newArr=[];
/* while(smallNum <= bigNum){
   newArr.push(smallNum);
   smallNum++;
 }*/
  let scm = bigNum;
   
  while(true){
    let conditionIs = true;
      for(let i= smallNum; i <= bigNum; i++){
       if(scm % i !==0){
         conditionIs = false;
         break;
         }    
       } 
    if (conditionIs){
      return scm;
    } else {
      scm++;
    }
    
 }
}


console.log(smallestCommons([1,13]));
   **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Safari/605.1.15

Challenge: Smallest Common Multiple

Link to the challenge:

This is a big red flag that you’ve designed slow code.

You can somewhat improve your code by increasing scm by a much better value than 1.

This is a hard challenge. I recommend people look up algorithms on Wikipedia for this challenge.

1 Like

You are right. I did sense using

while(true)

was not the best approach. I just didn’t know what else to do. I will continue to work on this. Thanks for your feedback!

Changing this line

Will make your code faster.

But, I still recommend putting a condition in the while loop. What number is guaranteed to be a multiple of every number in the range?

1 Like

I think the number that is guaranteed to be multiple of every number is the highest of the two numbers we are provided in the array.
Thanks much @JeremyLT

I don’t think that works? If you have [4, 6], the SCM is 60, which is bigger than 6. But what about 4 * 5 * 6?

1 Like

thanks for this. Great point… I’m just not sure if this would always be true.
[1,4] the scm would be 12 and not 24 no?

I’m just saying that the SCM can’t be bigger that the product of all numbers in the range, which lets you remove the while true.

1 Like

true true true. Thanks a lot for this!!

1 Like