Code Efficiency: Any Quick Way to Determine?

Hello,
I was wondering if anyone can tell me if there’s any way to calculate/determine how efficient/not efficient one’s code is. In the following code below, which is my noob-solution to the “Smallest Common Multiple” algorithm challenge, I assume that if I coded something like Euclidean’s algorithm into my code (I notated where I’m referring to below somewhere mid-way through the code) to determine the LCM of the numbers being checked, that the code would be more “efficient”. Actually, I assumed the code wouldn’t even work without figuring specific LCM’s but it did. The code passed but I feel a bit guilty about proceeding without something more “efficient”. Can someone explain how I, as a noob and not very naturally mathematically gifted, could determine the efficiency of one version of code vs. another version?

function smallestCommons(arr) {
  if (arr[0] > arr[1]){                     //sorts array into ascending order
    arr.push(arr.shift());
  }
  let aArr = arr[0];
  let bArr = arr[1];  
  let betweenArr = [];
  for (let i = aArr; i <= bArr;i++){ betweenArr.unshift(i)};//arr of numbers between a & b
  console.log(betweenArr);
  let a = betweenArr[0];
  let b = betweenArr[1];
  
  let lcm;
  lcm = ((a*b)/b); // .  ** PERHAPS THIS COULD BE MORE PRECISELY DEFINED USING THE EUCLIDEAN ALGORITHM? **
    
  let varPass;
  let lcmControl = lcm; //keeps a static lcm value in order to add to lcm for tests
  while (varPass = "not ok"){
    for (let i = 0; i < betweenArr.length; i++){
      if ((lcm % betweenArr[i]) != 0){
        varPass = "not ok";
        lcm += lcmControl;
      }
    }   
  }                                       

console.log(lcm);
return lcm;

}
smallestCommons([23,18]);

If by “efficient” you mean performant/fast, you can empirically find out how performant your code is using tools like jsPerf. You can also compare the performance of your solution vs. other solutions. No math knowledge required.

1 Like

Exactly the sort of thing I was talking about! Thanks!