# Smallest Common Multiple - Can someone explain this solution?

Smallest Common Multiple - Can someone explain this solution?
0

#1

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.

#2

It works. You can throw in some console log statements to see what’s happening to `i` and `mltple` as the for loop executes.

The basic idea is that whatever the smallest common multiple is, it will be a multiple of max. So the code just checks every single multiple of `max` starting from the lowest until it reaches one that can be evenly divided by all the integers between max and min.

For the case where `max = 5` and `min = 1`, it would go like this (in plain English):

mltple == 5

• Is 5 divisible by 5? Yep. Go on!.
• Is 5 divisible by 4? Nope. Add 5 to `mltple` and reset the for loop

mltple == 10

• Is 10 divisible by 4? Nope. Add 5 to `mltple` and reset the for loop

mltple == 15

• Is 15 divisible by 4? Nope. Add 5 to `mltple` and reset the for loop

mltple == 20

• Is 20 divisible by 4? YES, finally. Go on!
• Is 20 divisible by 3? Nope. Add 5 to `mltple` and reset the for loop.

mltple == 25

• Is 25 divisible by 4? Nope. Add 5 to `mltple` and reset the for loop.

…and so on through 30, 35, 40, 45, 50, and 55 until we reach 60, where it will go like this:

mltple == 60

• Is 60 divisible by 4? Yes. Go on!
• Is 60 divisible by 3? Yes. Go on!
• Is 60 divisible by 2? Yes. Go on!
• Is 60 divisible by 1? Yes. Go on!

ALL DONE! LET’S GO GET A BEER OR SOME GUMMY BEARS!