Smallest Common Multiple last 2 tests not working

Smallest Common Multiple last 2 tests not working
0

#1

My code works in Chrome console but not in fcc for some reason:

//noprotect

function smallestCommons(arr) {
  let sorted = arr.sort((a, b) => {
    if (a < b) {
      return a + b;
    }
    return arr;
  });
  
  let range = [];

  for (let i = sorted[0]; i >= sorted[1]; i--) {
    range.push(i);
  }

 function lcm(a, b) {
    
    for (let j = 0; j <= 100000000; j+=a) {
      let multipleA = a + j;
      
      if (multipleA % a === 0) {
        for (let k = 0; k <= multipleA; k+=b) {
          let multipleB = b + k;
          
          if (multipleB % b === 0 && multipleB === multipleA) {
            return multipleB;
          }
        }
      }
    }
  }

  return range.reduce((x, y) => {
    return lcm(x, y);
  });
}


smallestCommons([23, 18]);

i’ve tried adding // noprotect to disable infinite loop tracking but it seems like it’s still detecting something. it seems to be stopping when x and y are passed into the function as 106260, 19


#2

Your algorithm is not efficient enough to not trigger the infinite loop protection. In the new curriculum, there is no way to disable infinite loop protection, so you are forced to rethink your approach here.

My suggestion is to first figure out an efficient algorithm for how you would find the lcm for just two numbers. Once you can do that, then you would need to think how you could iterate through range array and calculate the lcm for the first two, then take that result (let’s call it result) and next find the lcm of result and the 3rd element, and so forth. At the end of this process, you will have the lcm for all the numbers in range.

Hint: That arbitrary upper limit (100000000) of your outer for loop in lcm is killing your efficiency.


#3

Turns out the second for loop in the lcm function was totally unnecessary:

function smallestCommons(arr) {
  let sorted = arr.sort((a, b) => {
    if (a < b) {
      return a + b;
    }
    return arr;
  });
  
  let range = [];

  for (let i = sorted[0]; i >= sorted[1]; i--) {
    range.push(i);
  }

 function lcm(a, b) {
    let multiple;

    for (let j = 0; j <= 100000000; j+=a) {
      multiple = a + j;
      
      if (multiple % b === 0) {
        return multiple;
      }
    }
  }

  return range.reduce((x, y) => {
    return lcm(x, y);
  });
}


smallestCommons([23, 18]);

This one ended up passing. Thanks for alerting me to an inefficiency issue!
As far as the arbitrary limit for the outer loop, i haven’t yet figured out a better solution but i’ll come back to it.