首页 > 解决方案 > 需要帮助来弄清楚这段代码是如何工作的

问题描述

所以在 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;  
    }

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

标签: javascript

解决方案


请参阅内联注释:

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;
}

推荐阅读