javascript - 我查找 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 提供的测试。除最后一项外,所有测试均通过。
解决方案
推荐阅读
- python - PyQt5 - 使用新的 pandas DataFrame 更新 TableView 时出现问题
- java - 如何将 Docker 容器作为持久服务器运行?
- spring-boot - 使用 JUnit 5 和 EmbeddedKafkaBroker 在 Spring Boot 应用程序中测试 Apache Kafka 集成
- pytorch - PyTorch:cuda 内存不足但剩余内存足够(添加错误消息)
- r - UTM 的范围和纬度的投影
- flutter - 颤振块中的状态或事件没有改变
- flutter - 有没有办法在构造函数中用不透明度定义颜色?
- docker - Kafdrop - 无法使用 bitnami/kafka 连接到 Kafka 集群设置
- python-3.x - Python3 - EC2 - smtplib - OVH:错误“[Errno 104] 对等方重置连接”
- sumo - 必须在 traci setRoute 中指定 SUMO 中的分割边?