Can anyone help me explain how this solution works? This is one of the solutions of the problem from :
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple
Here is the solution :
function smallestCommons(arr) {
var max = Math.max(arr[0], arr[1]);
var min = Math.min(arr[0], arr[1]);
var mltple = max;
for(var i = max; i >= min; i--){
if(mltple % i !== 0){
mltple += max;
i = max;
}
}
return mltple;
}
console.log(smallestCommons([1,5]));
Here is the explanation I can come up with.
// max = 5
//min = 1
//mltiple = 5;
/* for (i = 5 ; 5 >= 1 ; i-- ) {
if (5 % 5 !==0 ) = answer is 0, false
if (5 % 4 !==0 ) answer is 1, 1st true
if (5 % 3 !==0 ) answer is 2, 2nd true
if (5 % 2 !==0 ) answer is 1, 3rd true
if (5 % 1 !==0 ) answer is 0 , false
5 = 5(This is the original Multiple) + 5(1st true) + 5(2nd true) + 5(3rd true) = This should be 20
5 = 5 --> What does this do?
4 = 5 --> What does this do?
3 = 5 --> What does this do?
2 = 5 --> What does this do?
1 = 5 --> What does this do?
}
return mltple should be equal to 20?
*/
This will be a big help if someone can explain it.
Thanks.