Hello! I had tried to solve the challenge a lot of times before I used the hint, but I can’t still understand how this code executes.Please help me to understand it.
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;
}
smallestCommons([1,5]);
I tried to do my own, but I was stuck in the middle and couldn’t go further, so I decided to use the hint.I’m just asking to expain how the code works and that’s it. I can’t understand how the for loop works.
Hope this helps, if not feel free to ask what is the part where you get stuck.
function smallestCommons(arr) {
// declare 2 vars called max and min that have the value of Math.max operations
var max = Math.max(arr[0], arr[1]);
var min = Math.min(arr[0], arr[1]);
// The reason to have something declared twice like this is for functions where one of this will be changing as the function goes on:
var mltple = max;
// The value of i, which starts on max will decrease by one (i--) until is bigger or equal to min (i>=min)
for(var i = max; i >= min; i--){
// If the remainder of the division is different to 0, add max to mltple
// mltple += max is the same as mltple = mltple + max
if(mltple % i !== 0){
mltple += max;
i = max;
}
}
// when the condition i >= min is met, return the mltple
return mltple;
}
smallestCommons([1,5]);
Thank you very much for your help,but I don’t understand the loop.So this is how I see it:
var mltple = 5 ////because var max = 5
///////FIRST TIME/////////
for(var i = 5; 5 >=1; 5--){
if(5 % 5 !== 0)//// BREAK, it's false, check another one
}
///////SECOND TIME/////////
for(var i = 4; 4 >= 1; 4--){
if(5 % 4 !== 0)//// OK, it's true
5 += 4;////// it's 9
i = max; /////// So from now on I can't get it right whether i = 5 or 4(because initially var max = 5) and what is going on inside the loop.
}
/
Yeah looking at it again it dosn’t make much sense, where did you get this solution? I was looking at the solution here and it does it in a different way, the condition after if(mltple % i !== 0){ should add elements to an array, not add each other, I’ll try to test this later.