【问题标题】:Why does freecodecamp not let my while loop continue?为什么 freecodecamp 不让我的 while 循环继续?
【发布时间】:2021-07-18 16:59:44
【问题描述】:
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]) 应该返回 360360。

smallestCommons([23, 18]) 应该返回 6056820。

代码按以下步骤工作:

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

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

reference

【问题讨论】:

  • 您似乎从未将check 设置为true。因此,退出循环需要 (countDown(arr[1], two[two.length - 1]) == true 评估为 true
  • 顺便说一句,函数countDown() 可以更好地命名。我很确定它的目的不是倒计时。
  • 比较你的代码和this
  • @RobertHarvey 我不确定如何合并它。另请注意,我的数学很差。
  • 所以只需浏览我发布的链接中的代码,执行您脑海中代码的每一步。无论如何,您都需要学习如何做到这一点。另见ericlippert.com/2014/03/05/how-to-debug-small-programs

标签: javascript loops infinite-loop infinite


【解决方案1】:

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

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]))

【讨论】:

    【解决方案2】:

    我发现它超时的原因是它效率不高并且循环次数过多。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-11
      • 1970-01-01
      • 2021-04-09
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多