Tell us what’s happening:
So, this is a little odd. I’m getting correct values until the numbers get very large. I’m guessing this has to do with floating point processing, but when I use the answer code it works fine. In theory, I think my code should work, so I’m a little confused where my inefficiency is.
any help is appreciated.
EDIT: Yeah, I solved it. in the while, loop, I just changed:
ans = index * Math.min(...newArr);
to
ans = index*newArr[0]*newArr[1];
I guess the time limit must be really strict, as I also made a bunch of other small optimizations in order to fit in.
Your code so far
function smallestCommons(arr) {
arr = arr.sort((a,b) => a-b);
var newArr=[];
var found = false;
var ans = 0;
var index = 0;
for(var i = Math.max(...arr); i >= Math.min(...arr); i--){
newArr.push(i);
}
while(found===false){
index++;
ans = index * Math.min(...newArr);
for(var i = 0; i < newArr.length; i++){
if(ans % newArr[i] !== 0){
found = false;
break;
}else if(i===newArr.length-1){
found = true;
return ans;
break;
}
}
}
return ans;
}
console.log(smallestCommons([23,18]));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple