Smallest Common Multiple- last two cases unsolved

Tell us what’s happening:
I am unable to solve last two test cases with my code. Can anyone help me with the problem? First four test cases are okay.

Your code so far


function smallestCommons(arr) {

    var min = Math.min(...arr);
    var max = Math.max(...arr);
    var arr = [];
    var c = true;
    var i = 2;
    var j = 0;
    var flag = 0;
    var commonNum = 0;
    //pushing the values into array
    for (min = min; min <= max; min++) {
        arr.push(min);
    }
    //main loop for finding the common multiple
    while (c) {
        flag = 0;
        for (j = 0; j < arr.length; j++) {
            //checking if a certain number is divisible by the all arr values
            if (i % arr[j] == 0) {
                flag++;
            }
        }
        //if flag is equal to the arr length we found the common multiple
        // storing the common value
        // stopping the loop by making it false
        if (flag == arr.length) {
            commonNum = i;
            c = false;
        }
        i++;
    }
    console.log(commonNum);
    return commonNum;
}
smallestCommons([1,6]);

Your browser information:

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

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

Your function does calculate the correct answers but takes quite a few iterations to come up with those correct answers. You are most likely tripping the Infinite Loop Protection in the FCC environment.

You are testing every number consecutively as a possible SCM and that is resulting in a lot of looping. In the last two cases well into the millions of iterations. You’ll need to eliminate some of those numbers that could not possibly be SCM without actually testing them.

Just a hint to get you started - any SCM for [1,5] would have to be 5 or some multiple of 5 so testing 6, 17, 38, etc would all be needless effort. That hint alone might not be enough to pass those last two though. You’ll have to increase the efficiency of your algorithm by testing fewer numbers, limiting yourself to numbers that have a more reasonable chance at being SCM.

thanks man. appreciate it :slight_smile:

You are welcome. Search the forum for old posts on this challenge. This issue comes up frequently and you’ll find clues in some of those posts.