为什么 freecodecamp 不让我的 while 循环继续?

Why does freecodecamp not let my while loop continue?

function checkRange(num, temp) {
  for (var i = 1; i < num; i++) {
    console.log(temp % i, i, temp);
    if (temp % i != 0) {
      return false;
    }
  }
  return true;
}

function smallestCommons(arr) {
  arr.sort((a, b) => {return a > b})
  var two = [arr[1]];
  var check = false;
  while (check == false) {
    two.push(two[two.length - 1] + arr[1])
    if (checkRange(arr[1], two[two.length - 1]) == true) {
      check = true;
      return two[two.length - 1];
    }
  }
  console.log(two);
  // not sure what to do with this
  return two[two.length - 1];
}


smallestCommons([1, 13]);

所以我意识到这可能是一个无限循环,但我想知道为什么会这样。

我的代码不适用于:

smallestCommons([1, 13]) 应该 return 360360.

smallestCommons([23, 18]) 应该 return 6056820.

代码按以下步骤运行:

获取较低的数字作为第一个索引(排序)

创建一个循环,不断将最后一个索引与 arr[1] 相加,并验证是否可以将计数到 arr[0] 的每个数字均分给数组的最后一个元素。

reference

这是我学习时的回答​​:

function checkall(arr, lcm) {
  let num1 = arr[0]
  let num2 = arr[1]
  // Get the start number
  let first = (num1 < num2) ? num1 : num2;
  // Get the end number
  let last = (num1 > num2) ? num1 : num2;
  while (first != last) {
    // Check if lcm is divisble
    if (lcm % first != 0) {
      // If not then get an lcm of the number and existing lcm
      lcm = getlcm(first, lcm)
    }
    // Increment first
    first++
  }
  // Return the end lcm
  return lcm
}

function smallestCommons(arr) {
  // Get the two numbers
  let num1 = arr[0]
  let num2 = arr[1]
  // Feed the array and lcm into the checkall function
  return checkall(arr, getlcm(num1, num2))
}

function getlcm(num1, num2) {
  // Get the minimum number out of both
  let min = (num1 > num2) ? num1 : num2;
  while (true) {
    // Check if a number is divisible by both
    if (min % num1 == 0 && min % num2 == 0) {
      // If matches, this is the lcm
      // Break the loop and return the lcm
      return min
      break;
    }
    // Increment the number
    min++;
  }
}


console.log(smallestCommons([1, 13]))
console.log(smallestCommons([23, 18]))
console.log(smallestCommons([2, 10]))

我发现它超时的原因是因为它效率低下并且循环太多。

Keshav 的回答似乎也有很多循环,所以我不太确定为什么它不会超时...