Smallest Common Multiple-Am I on the right track? Thanks!

Smallest Common Multiple-Am I on the right track? Thanks!
0

#1

This is my code so far:

When I console.log at line 8, I get [1,5], the expected result. However, when I console.log after line 14, I get null. Might anyone know why this is? Thanks!


#2

Can you post the actual code? It makes it easier for us to test without retyping the code from your screenshot.

To you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#3

I’ve changed my code. Trying to wrap my head around this problem. Also, wondering if I’m taking the right approach.


function smallestCommons(arr) {
  
  //sort array of numbers.
  arr.sort(function(a, b){
    return b-a;
  });
 
  //create new array
  var newArr = [];
  //array should contain two numbers and all numbers in between from greatest to lowest
  for(var i = arr[1]; i < arr[0]; i++) {
  newArr.push(i);
  }
  
  //take largest number, assign it to var lcm (lowest common multiple), divide other numbers into it. If all remainders are zero, break.
  var lcm = arr[0];
  for(var j = 1; j < newArr.length; j++) {
    if (lcm % arr[j] == 0) {
      return lcm;
    } else {
      lcm *= 2;
    }
  }
  //multiply largest number by two and divide other numbers into it again. If all remainders are zero, break.
  
  
  
  //return arr;
  
}


smallestCommons([1,5]);

#4

Before the for loop, you assign lcm the highest value in arr, so lcm is 5, then in the first iteration of the for loop, you check to see if the remainder of lcm divided by 1 is 0. Well, 5 divided 1 is 5 with a remainder of 0, so you are returning lcm (which is 5).


#5

Should I use the .every method?


#6

That would depend on how and where you plan to use it.