Tell us what’s happening:
I can’t figure out what’s wrong with my code. It passes ALL tests except for the final one which requires me to find the smallest common multiple of 23 and 18 given the requirements.
The idea behind my code is:
the LCM must be multiple of the max number ,so I check the multiples of the max number and check if it can be evenly divided by every item using array.every() function.
I have two issues here:
- if I use “console.log(temp);” the [1,13] will fail too, if comment out, it will pass;
- if I change maxItem to arrR[0]*arrR[1], it will pass all test cases; but if set maxItem to arrR[0], it will pass all but the last one case [23,18].
I spent a lot time finding the error ,but I still failed to find the cause of it.
Please help me , thanks a lot.
Your code so far
function smallestCommons(arr) {
let i;
var arrR=[];
//get the array
for(i=Math.max(...arr);i>=Math.min(...arr);i--){
arrR.push(i);
}
//get the lcm
var maxItem = arrR[0];
var temp;
for(i=1;;i++){
temp = maxItem*i;//the lcm must be multiple of max number,so check
//console.log(temp);
if( arrR.every(el=> temp%el==0) ){
return temp;
}
}
}
smallestCommons([23,18]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple