Least common multiple; intermediate algorithm scripting


I was wondering why my code wouldn’t sufficiently solve the problem. exercise: find least common multiple of two numbers (arr) and all numbers in between them.
Here is the code.

function smallestCommons(arr) {

    let tween = []
    if (arr[0] > arr[1]){
      for (let i=arr[1]; i <= arr[0]; i++){
        tween = tween.push(i)
// made new array of all the numbers from arr[1] to arr[0]
    let n = 0;
    var a = 0;
    for (var n = (arr[0]*arr[1])+1; n < (arr[0]*1000); n++){
      for (var a = 0; a < tween.length; a++){
      if (n%arr[0] === 0 && n%arr[1] === 0 && n%tween[a] ===0 ){
        return n}
    }return n
    //start at both numbers multiplied together + 1, go to bigger number x 1000. just for good measure to get a test case to make sure I'm on right track. Then check every number to make sure it divides by both starting numbers as well as all numbers in new array tween. return that number if it checks out. 


I realize that there is the whole set of cases where arr[1] > arr[0] but I can't get this way to work for any of the test cases. Also does anyone know why I can't use console.log() anymore to print stuff to the console? 


if you ask for help it is greatly appreaciated if you also would include the challenge link

This is a great place to practice some Google-foo. As a general rule, if you want to find a particular number, unless you can ensure the list is small, looping over all possible candidates is a very bad idea. This will take a very long time.

At the very least, you should only check multiples of one of your known values. a+1 is almost never a multiple of a, for example.

Now, to your code.

I think your if statement doesn’t do what you believe. Let’s trace a specific case.

Let arr = [5, 8].

Then tween = [6, 7].

Your code will return 120 but 120 % 7 = 1! Why did your if statement let this happen?!?

Yes, of course my apologies.


Hmm. Because I said

a < tween.length?

so tween length in this case would be 2 so a could be 0 or 1 which would be tween[0] and tween[1] which is both 6 and 7. Or oh because it just needs to have ONE tween[a] pass, which would be

 a = 1, tween[1] = 6.
 Doesn't even need 7 to pass?

There you go! Only one of the tween values needs to pass with your current if statement.

Your a loop would somehow need to know how things turned out on other values of a for this approach to work.

1 Like

Thank you for explaining that.

No problem! You can still get this approach to work by keeping track of if all tween values worked, but be careful because the tests won’t pass if the loop takes too long.

1 Like