javascript - 需要帮助来弄清楚这段代码是如何工作的
问题描述
所以在 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;
}
推荐阅读
- python-3.x - Pandas 访问一系列矩阵的第一个条目
- ios - 如何将渐变层放置到没有框架的 UIImageView 上
- android - 应用程序在模拟器上部署失败,但预览器在 Xamarin 中工作......我不知道出了什么问题?
- python - 使用经过训练的模型层在 keras 中创建另一个模型
- jquery - 图像滑块播放/暂停适用于按钮但不适用于悬停
- reactjs - 验证后调用保存方法
- python - 从 ctypes 访问大内存缓冲区时的段错误
- reactjs - 隐式获取任何绑定元素子项的类型错误
- java - 无法解析名称为“spring”的 servlet 中名称为“streamrecords”的视图
- c++ - 在 VS 代码中使用全局变量时出现“未定义的引用”错误