微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么 freecodecamp 不让我的 while 循环继续?

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

解决方法

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

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 的回答似乎也需要很多循环,所以我不确定为什么它不会超时......

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。