Smallest common works on node, not working on freecode

Smallest common works on node, not working on freecode
0

#1

i have this code for the smallest common multiple problem

// get all numbers between first and second includes
function getAllNum(first, second) {
    allNum = [];
    for(i = first; i <= second; i++){
        if(i != 1) {
            allNum.push(i);
        }
    }
    return allNum;
}

// help reduce to multiply all numbers in an array
function getMax(total, num) {
    return total * num;
}

function smallestCommons(arr) {
    arr.sort(function(a, b){return a - b;});
    var allNum = getAllNum(arr[0], arr[1]);
    var maxMultiple = allNum.reduce(getMax);
    i = 2;
    var smallestMultiple;
    whileloop: while(i <= maxMultiple) {
        var isMultiple = true;
        outerloop: for(j=0;j<allNum.length;j++){
            var multipleJ = i * allNum[j]; 
            innerloop: for(k=allNum.length - 1; k >= 0; k--){
 
                if(multipleJ % allNum[k] == 0){
                    isMultiple = true;
                } else {
                    isMultiple = false;
                    break outerloop;
                }
            }
        }
        if(isMultiple) {
            smallestMultiple = i;
            break whileloop;
        }
        i++;
    }
    return smallestMultiple;
}



smallestCommons([23, 18]);

if i run this code with node i obtain

$ time node smallest_common_multiple.js
maxMultiple : 72681840
smallestCommons([23, 18]) : 6056820

real	0m0.119s
user	0m0.115s
sys	0m0.005s

pero si pongo el mismo codigo en freecodecamp y i push run test i obtain

 smallestCommons([1, 5]) should return a number.
smallestCommons([1, 5]) should return 60.
smallestCommons([5, 1]) should return 60.
smallestCommons([1, 13]) should return 360360.
smallestCommons([23, 18]) should return 6056820.

help!
(by the way i enjoy this course :slight_smile:)


#2

The loop you have could potentially, given the right parameters, run indefinitely - there’s a guard on the tests to force them to timeout quickly in that case - first three test run very quickly so there isn’t an issue, but as the numbers get larger, the protection kicks in.

If you change the line at the bottom to one of the failing tests, eg smallestCommons([1, 13]);, it’ll tell you how to get around the issue - you just need to add // noprotect as the first line in your code to override the protection.


#3

works like charm!
thanks dan