Tell us what’s happening:
I wrote comments on what it supposed(for me heh) … what i wanted from this code, basically i wanted to kind of copy real LCM operation? Starting from 2 and checking if given num from array is divisible of that num (i)…
If true, adds that num to new array and divide every num by (i) and so on till every num from sortedArr gets devided to 1? and then just multiply it with reduce? And btw it does work(checks) for 1-5 range when lcmArr.push(i) is last thing in last if statment, tho doesnt really makes sense to me why. Any hints where i could go with this, i really dont want to check any solutions(feeling like im kinda close with my own?)
Oh and btw, for example for first one (1-5) console lcmArr returns [2,3,5]… it does miss that second 2… not really sure why, i mean i figure out by consoling sortedArr that what was 4 is now 2 and not 1 at the end… Shouldn’t array.some() and loop after it take care of that, by dividing it untill there is no more to be divided by (i)?
Your code so far
function smallestCommons(arr) {
// Sorted Array and needed variables
let sortedArr = [];
let holderArr = arr.sort((a, b) => a - b);
for (let i = holderArr[0]; i <= holderArr[1]; i++) {
sortedArr.push(i);
}
let lcmArr = [];
//Iterating over sortedArr to check if any num in arr is div by current number from //loop, if true, push that num into new arr, and div every divisible num by that
// number. Keep checking it till there isnt num in arr to div with it, go to next num
for (let i = 2; i <= sortedArr[sortedArr.length-1]; i++) {
if (sortedArr.some(num => num % i === 0)) {
lcmArr.push(i);
for (let j = 0; j < sortedArr.length; j++) {
if (sortedArr[j] % i === 0) {
sortedArr[j] = sortedArr[j] / i;
}
}
}
}
console.log(lcmArr);
return lcmArr.reduce((a,b) => a * b);
}
smallestCommons([1,5]);
// for (let num = 2; true; num++) {
// if (fullArr.every(x => num % x === 0)) {
// console.log(num);
// return num;
// }
// }
// for (let i = 0; i < sortedArr[1]; i++) {
// var num = 2;
// while (true) {
// if (sortedArr.every(x => num % x === 0)) {
// console.log(num);
// return num
// }
// num++;
// }
// }
// let check;
// for (let num = 2; true; num++) {
// check = sortedArr.every(x => num % x === 0);
// console.log(check);
// if (check === true) {
// return num;
// }
// }
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36
.
Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple