Smallest Common Multiple: Random values are generating in console

Smallest Common Multiple: Random values are generating in console
0

#1

This piece of code generates random values in FCC console.
Would you help me to find out why this code generates random values for a specific test in FFC console but works correctly everywhere outside?
The failed test is written at the end.


function smallestCommons(arr) {
  arr.sort((a,b)=>a>b);
  let newArr = [];

  for(let i = 0; i <= arr[1] - arr[0]; i++) {
    newArr.push(arr[0] + i);
  }

  let found = false;
  let result = arr[1];

  while(!found) {
    found = newArr.every(x => (result % x) == 0);
    if(!found) result++;
  }

  return result;
}


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

Browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple


#2

This is a very common problem on this challenge. Excessive looping triggers the infinite loop protection in the FCC testing environment.

You function is testing every number as a possible candidate for SCM even though most of those numbers are not mathematically possible solutions. If the SCM is in the millions then your function iterates millions of times to find that SCM.

You’ll have to craft an algorithm that skips most of those that are not possibilities and tests only those that are more likely potential solutions.

There a quite a few posts on this topic. You might search the forum to see if any of those could help you. Smallest Common Multiple (or Least Common Multiple) is also a frequent intermediate mathematics topic so you might find a resource online that explains a pencil and paper mathematical solution that could be the basis for your coded algorithm.


Smallest Common Multiple..44