Wierd results, is it a bug?

For some reason the array [23, 18] is giving me different outcomes every time i run the script, while it works for the other cases. What’s bugging me the most is the randomness of those numbers, considering that there’s no random component in the script, so I was wondering if this could be caused by the browser (i’m using chrome), like having a limit on operations or similar.

Intermediate Algorithm Scripting: Smallest Common Multiple (i’m new in the forums, can’t post links)

function smallestCommons(arr) {

  //sort starting array in ascending order
  arr.sort((a, b) => {return a-b});

  //generate new array with all the intermediate values
  let newArr = [];
  for (let i = arr[0]; i <= arr[arr.length - 1]; i++) {
    newArr.push(i);
  }

  //check candidates until it finds the correct result
  let candidate = arr[arr.length - 1];

  while (!newArr.every((num) => {
    return (candidate % num) === 0; 
    })) {
    candidate += 1;
  }
  return candidate;
}


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

You are checking numbers one by one (candidate+=1), you are triggering the infinite loop protection

You need an algorithm that requires less resources

oh ok, I guess it’s not technically an error in the script (it’s definitely heavy on computation, but I did that to experiment with different stuff)

You will need to find a different way! You can try even more stuff!
If you need any inspiration, and you are not that strong in math, search maybe for math algorithms about this

oh I love math and I know of more ways to do it, I just did what I found more interesting and where I could learn more, instead of the most efficient way :grin:

edit: like I could have used the script from the previous exercise to find all the prime numbers, but I wanted to do something different and not copypaste

Copy-pasting your own code, having some functions that do predefined tasks is not a wrong approach, if you need a function that do a task that you have already written you go to use that function instead of writing a new one

indeed, but right now I’m trying to learn and experiment as much as possible, i’d rather try a different approach while resolving a similar exercise, instead of copypasting and have 50% of the exercise already done. The goal is not to complete the challenges but to learn while doing so :grinning:

1 Like