Tell us what’s happening:
Your code so far
function smallestCommons(arr) {
let newArr = [];
arr.sort((a,b)=>a-b);
for (let i = arr[0] ; i<arr[1] ; i++){
newArr.push(i);
}
return arr;
}
smallestCommons([1,5]);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple
I am only able to do this far at the moment.
I’ve stuck here for a while.
I’ve checked the math algorithm of the least common multiple.
I want to read some codes to help me understand better and I came across this code
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 don’t understand the logic of this code…
I tried to put a number inside, but am still confused.
For the first round of for loop, is
for(var i = max; i >= min; i--){
// i=5 ; i>=1 ; i--
if(mltple % i !== 0){
//if (5 % 5 !== 0){
// here 5 % 5 == 0 so the rest code will not excute.
mltple += max;
i = max;
}
}
then the second round is
for(var i = max; i >= min; i--){
// for(i = 5; i>=1 ; i--){
if(mltple % i !== 0){
//if (5 % 4 !==0){
mltple += max; //mltple = 5+5
i = max; // i = 5?;
}
}
then third round became
for(i = 5 ; i>=1 ; i--){
if (5% 3 !==0){
mltple += max; // mltple = 10+5
i = max; // i = 5;
for(i = 5 ; i>=1 ; i--){
if (5% 2 !==0){
mltple += max; // mltple = 15+5
i = max; // i = 5;
for(i = 5 ; i>=1 ; i--){
if (5% 1 !==0){
//5 % 1 == 0, so the code won't excute the line below and for loop is also finished. (because i = 1 now)
mltple += max;
i = max; // i = 5;
But then the value of return mltple;
is only 20.
Did I make any terrible mistake here???