Smallest Common Multiple - Overflow problem?

Yeah I ended up switching to Euclid’s algorithm for my final solution since this wasn’t working. Don’t think it’s worth debugging this really inefficient alternative since we know Euclid’s will be exceptionally better.

function smallestCommons(arr) {
  if (arr[0] < arr[1]) {
    arr.reverse();
  }
  var i = arr[0];
  var j = arr[1];
  var prod = 1;
  
  console.log(arr);
  var btwn = [];
  for (let k=i; k>=j; k--) {
    btwn.push(k);
    prod*=k;
  }
  console.log(btwn,prod);

  for (let f=0; f<btwn.length; f++) {
      console.log(btwn[f]);
    }
  function gcd(x,y) {
    if (y == 0) {
      return x;
    } else {
      return gcd(y,x%y);
    }
  }
  var lcm = btwn[0];
  for (let f=0; f<btwn.length; f++){
    var GCD = gcd(lcm,btwn[f]);
    lcm = (lcm*btwn[f]) / GCD;
  }
  
  return lcm;
}


smallestCommons([23,18]);
1 Like