Finding a solution for LCM challenge

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

Well, the first line makes use of Arrow Functions, the Ternary Operator, and Remainder Operator.

I suggest you give those a read, and, if you do not understand something specific, report back here :wink:

It is a lot of syntax to learn, though. So, do not expect to understand their ins-and-outs.

1 Like

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. :slight_smile:

3 Likes

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.

Ok thanks. I am going to search for methods to find LCM and GCD in math and I will try converting them.
Thanks for your help.

Good luck and happy coding! Don’t be too shy to ask for help or just use us as a sounding board.

1 Like

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. :smiley:

2 Likes

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.

1 Like