Hello,
so i was trying to solve the lcm javascript challenge; however, my code seemed to be very inefficient and i got an error. i got an infinite loop.
i finally found this snippet of code. but i didn’t how the first line works. in other words, i didn’t understand the syntax of the first line.
thanks
const gcd = (a, b) => a ? gcd(b % a, a) : b;
const lcm = (a, b) => a * b / gcd(a, b);
//Then use reduce on given array of integers:
[1, 2, 3, 4, 5].reduce(lcm); // Returns 60
My recommendation is that instead of looking at code solutions and trying to decipher them, look at the logical (mathematical) solution. I like Wikipedia’s. Then translate that into code yourself. You’ll end up with something more efficient and understand your code solution much better.
I read these articles and I understood what they meant; however, I am still finding a problem in understanding why that will work thus I will try the method the other person suggested.
Thanks for your help I understood the code.
so i came up with the following code which uses functions in i think es5. it is a lot easier for me to understand. i guess it is the same as the previous method as the one I sent before. I used the Euclidean Method thanks to your advice on searching wikipedia for methods. this is my code:
function smallestCommons(arr) {
let newArr = []
if (arr[0] > arr[1]) {
arr = [arr[1], arr[0]]
}
//console.log(arr)
for (let i=arr[0]; i<=arr[1]; i++) {
newArr.push(i)
}
//console.log(newArr)
function gcd(a,b) {
if (a==0) {
return b
} else {
return gcd(b%a, a)
}
}
function lcm(a,b) {
return (a*b)/gcd(a,b)
}
return newArr.reduce(lcm);
}
console.log(smallestCommons([23,18]));
Congratulations on working it out! Having the curiosity and drive to rework a problem until you feel good about it is definitely the right mindset to have for this field.
Nice work. That’s pretty close to how I would have coded it myself. One liners are fine and look slick, but I think that your code is pretty clear, especially if you add some comments to help future you remember what you did.