Hi,
I struggled with this smallest common multiple challenge for a while. I found a solution on stack overflow that looks super sexy and fairly simple but I’m having trouble understanding exactly what’s happening.
It would be really helpful if someone could break it down for me a little bit.
This is my first time posting, please let me know if I should do anything to improve my etiquette.
Thanks in advance!
function smallestCommons(arr) {
arr.sort((a,b) => a-b)
while(arr[0] < arr[1]) {
arr.splice(1,0, arr[1] - 1)
}
arr.shift() //how could I avoid this shift?
//everything below this line is what I need help understanding.
const gcd = (a, b) => a ? gcd(b % a, a) : b;
const lcm = (a, b) => a * b / gcd(a, b);
return arr.reduce(lcm)
//like, if I had this array [1,2,3,4,5], is lcm first comparing 1 and 2? what's happening here -> gcd(b % a, a)?
Sorry if these are obvious questions, I'm very new to coding.
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Smallest Common Multiple