Smallest Common Multiple challenge -- I can't figure out what's wrong with my code

Hey,

First timer. Anyone care to help me? I’m currently doing intermediate algorithm challenges. This one on finding the smallest common multiple for a range of numbers stumped me. This is my attempt below. I tried to add comments, but if any part of it isn’t clear, please let me know. My code works for all test inputs, except [1, 13] and [18, 23]. I honestly couldn’t figure out why.

Sorry if this is too long, as I’ve never done this before. Any tips or suggestions would be greatly appreciated!

function smallestCommons(arr) {
 // find the range of numbers
  arr.sort((x, y) => x - y);
  let range = [];
  let i = arr[0];
  while (i < arr[1] + 1) {
    range.push(i);
    i++;
  }
// divide n by each number in the range
  let n = 2;
  for (let i = 0; i < range.length; i++) {
    if (n % range[i]) { 
    // if n doesn't divide evenly, then increment n and start over
      i = 0;
      n++;
    }
  }
  return n;
}

That is a memory issue. I could not find anything else. I am really curios if anyone can see what is the problem here.

1 Like

I am running the function in node at the moment :)) over 500 MB of memory so far. I will come back with a print screen.

@camperextraordinaire Smallest Common Multiple - Overflow problem?

1 Like

Interesting fact:

 let functionCall = 0;

function smallestCommons(arr) {
  function isValidMultiple(m, min, max) {
    functionCall += 1;
    for (var i = min; i < max; i++) {
      if (m % i !== 0) {
        return false;
      }
    }
    
    return true;
  }
  
  var max = Math.max(arr[0], arr[1]);
  var min = Math.min(arr[0], arr[1]);
  var multiple = max;
  
  while (!isValidMultiple(multiple, min, max)) {
    multiple += max;
  }

  console.log(functionCall);
  return multiple;
}

console.log(smallestCommons([18,23]));

This code is similar to the “solution” above but will be successful because is running each loop inside a function call isValidMultiple.

The interesting fact is that the function smallestCommons it is called 263340 times in less than a second (on my test 8 ms)

Untitled.
This is how amazing JavaScript is.

Isn’t this a prime factorization question?

Why does the fact that the loop is running inside a nested function make any difference?

Prime factorization is only one of many valid approaches to solve this problem.