繁体   English   中英

需要帮助弄清楚这段代码是如何工作的

[英]Need help in figuring out how this code works

所以在 freeCodeCamp 上有这个挑战:

找到可以被两者以及这些参数之间范围内的所有序列号均分的所提供参数的最小公倍数。

该范围将是一个由两个数字组成的数组,不一定按数字顺序排列。

例如,如果给定 1 和 3,请找出 1 和 3 的最小公倍数,该倍数也可以被 1 和 3 之间的所有数字整除。 这里的答案是 6。

我在论坛上找到了一个非常简短的解决方案,但尽管绞尽脑汁几天,我还是无法弄清楚它是怎么回事。 这是代码。

    function smallestCommons(arr) {

      var max = Math.max(arr[0], arr[1]);
      var min = Math.min(arr[0], arr[1]);
      var mltple = max;

      for(var i = max; i >= min; i--){
        if(mltple % i !== 0){
          mltple += max; 
          i = max;
        } 
      }

      return mltple;  
    }

有人可以解释一下发生了什么吗? 它的简短很有趣,但很想知道发生了什么。

见内嵌评论:

function smallestCommons(arr) {
  // given: arr is an array containing two integers
  // they are accessed using their indexes

  // figure out which of the numbers is greater
  var max = Math.max(arr[0], arr[1]);

  // figure out which of the numbers is lesser
  var min = Math.min(arr[0], arr[1]);

  // declare the variable mltple which will hold the answer
  // it can't be less than the greater of the two numbers in arr
  // so set it to max
  var mltple = max;

  // start with the larger of the numbers in arr (i.e. max)
  // count down and run the following loop for each number 
  // until we reach min
  // i will keep track of the number as it counts down
  for (var i = max; i >= min; i--) {

    // check to see if there is a remainder when mltple
    // is divided by i
    // if there is, then mltple must not be 
    // the least common multiple
    if (mltple % i !== 0) {

      // as long as there's no remainder,
      // we increase mltple by max
      mltple += max;

      // set i to max and begin the countdown loop again
      i = max;
    }
    // if there is no remainder when dividing mltple by i
    // then i is decreased by 1 and the loop runs again
    // when i reaches a number less than min, the loop exits
    // and the function returns the value of mltple
  }

  return mltple;
}

基本上,代码采用变量 multple(将其初始化为 max)并检查 multple 是否是 max 和 min 之间所有值的倍数。 如果为真,则返回它。 否则,它会在 multple (multiple+=max) 中增加 max,并再次重复从 i=max 开始的步骤,并检查从 max 到 min 的所有值。 希望这可以帮助。 如果您仍然不明白,请告诉我。

顺便说一句,我认为这段代码正在找到位于最大值和最小值之间的所有值的公倍数。 因为它从最大值开始循环到最小值,并根据所有值检查多个值。

由于我们试图找到公倍数,因此两个数的最小公倍数可能(但不一定)是两者中较大的数。 所以,这就是我们开始测试的地方,即。 从两者中较大的数量开始。 取这两个数为2和3。2的倍数是2、4、6、8……等等,3的倍数是3、6、9、12…………等等。 这里的公倍数只能是较大数的倍数,即 3。这就是变量 mltple 每次都增加较大数的原因。 接下来,我们将遍历所有应该根据要求划分 mltple 的数字。 一旦满足所有条件,我们就会返回答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM