Smallest Common Multiple - stuck

Smallest Common Multiple - stuck
0

#1

I’ve just about got this but I’m struggling with the last test. All the other tests work and the array I create looks ok
Any idea what I’ve done wrong?

function smallestCommons(arr) {

  var newArr = [];
  arr.sort(function(a, b){
    return a - b;
  });
  console.log(arr);
  for (var i = arr[0] ; i <= arr[1]; i++){
    newArr.push(i);
    console.log(newArr);
  }
function gcd(i, j) {
    if (j === 0)
        return i;
    else
        return gcd(j, i % j);
    }
    var lcm = newArr[0];
    for (var i = newArr[0]; i < newArr.length; i++){
      var ans = gcd(lcm, newArr[i]);
      lcm = (lcm * newArr[i]) / ans;
      console.log(lcm);
    }
  
  return lcm;
}


smallestCommons([23, 18]);

#2

A post was split to a new topic: Smallest Common Multiple failing last test


#3

@CoMIYC69

In the test case of smallestCommons([18, 23]), before the for loop begins, newArr looks like:

[ 18, 19, 20, 21, 22, 23 ]

Then, in the following for loop, you start i as newArr[0]. In this case newArr[0] is 18. Then your for loop exit condition of i < newArr.length is checked. Since newArr.length is 6, the condition evaluates to false ( because 18 < 6 is false) and the no code in the for loop executes. Since the last value of lcm before the function exist is determined before the for loop (seen below), your function returns 18.

lcm = newArr[0]

#4

Thanks…
So is the problem that I’m trying to access newArr.length?
How do I set up a for loop with the last value as the comparison instead of the array length?


#5

The last value in newArr? If that is your question, then surely you already know how to use the length of an array to reference the last element in the same array. In fact, you created that value at the beginning of your function when you sorted arr. Which element in arr has the last value in newArr.


#6

Thanks
Still confused over accessing the last item in the newArr
I tried this but it fails all together

i < newArr[newArr.length - 1]

#7

You have correctly referenced the last element in newArr above. You could have also written:

i < arr[1]

However, the way you are using recursion in the for loop is causes a Range Error because you maxed out the call stack.


#8

Thanks

O-Boy! What does a a Range Error mean and how do I fix it?

Maximum call stack size exceeded


#9

It means your function was called more times than the memory in the stack could hold. It is time to rethink your approach to this problem.