javascript – 最小的公共多个 – 无限循环

我正在进行一项名为Smallest Common Multiplier的freeCodeCamp练习.练习的目的如下:

Find the smallest common multiple of the provided parameters that can
be evenly divided by both, as well as by all sequential numbers in the
range between these parameters.

The range will be an array of two numbers that will not necessarily be
in numerical order.

e.g. for 1 and 3 – find the smallest common multiple of both 1 and 3
that is evenly divisible by all numbers between 1 and 3.

我以为我可以通过将传递给函数的数组中的元素从最小值排序到最大值来保存它,然后检查所有数字的for循环,无论数字%x === 0.我然后将所有内容封装在一个while循环检查分隔符的数量(如果分隔符的数量小于我正在检查的最高数量,重复该过程.

好像我写了一个无限循环,崩溃了我的浏览器.

function smallestCommons(arr) {

  //sort from smallest to largest
  arr.sort(function(a, b) {
    return a-b;
  });

  var result = 1;
  var divisors = [];

  //while number of divisors !== last number to check
  while(divisors.length < arr[1]) {
    //check if number divides result
    for(var x = arr[0]; x < arr[1]; x++) {
      //if it divides result
      if(result % x === 0) {
        //push it to divisors
        divisors.push(x);
      }
      else {
        //clear divisors
        divisors = [];
      }
    }
    //check next number
    result++;
  }

  return result;
}


smallestCommons([5,1]);

你能指出我做错了什么,并指出如何进行练习吗?

最佳答案 请注意,您在函数的else部分中清除了divisors数组.

那样你就无法通过条件divisors.length> = arr [1]

但是,您对LCM的实施根本不起作用

点赞