首页 > 解决方案 > 我查找 n 个数字的 LCM 的功能仅在某些类型的情况下失败。我的代码有什么问题?

问题描述

几个月前,我刚开始自学基本编程。如果我的问题看起来很愚蠢,请原谅。

在尝试解决 freecodecamp 的 Javascript 挑战之一时,我编写了以下代码来找出数组中 n 个数字的最小公倍数 (LCM)。我的代码通过了所有测试,但最后一个。freecodecamp 也没有显示任何错误。所以我无法理解只有最后一次测试失败的代码有什么问题?

作为函数输入的数组 (arr) 由 2 个数字组成,问题陈述要求找到该范围内所有数字的 LCM(包括这 2 个数字)。

function smallestCommons(arr) {
  function allNumsArr(x) {
    let y = [];
    for (let i = Math.min(...x); i <= Math.max(...x); i++) {
      y.push(i);
    }
    return y;
  };

  var allInArr = allNumsArr(arr);

  function findHCF(x,y) {
    if (x == 0 || y == 0) {
      return 0;
    } else if (x === y) {
      return x;
    } else {
      return findHCF(Math.max(x,y) - Math.min(x,y), Math.min(x,y));
    }
  };
  /* The above is calculated as per the Euclid's algorithm to find the HCF/GCD */

  var hcfOfAll = allInArr.reduce((a,b) => findHCF(a,b));
  return allInArr.reduce((a,b) => ((a * b)/(findHCF(a,b))));
};
console.log(
smallestCommons([1, 5]), //should return a number.
smallestCommons([1, 5]), //should return 60.
smallestCommons([5, 1]), //should return 60.
smallestCommons([2, 10]), //should return 2520.
smallestCommons([1, 13]), //should return 360360.
smallestCommons([23, 18]), //should return 6056820.
)

以下是 freecodecamp 提供的测试。除最后一项外,所有测试均通过。

标签: javascript

解决方案


推荐阅读