Javascript 需要了解此代码如何工作的帮助吗
因此,freeCodeCamp面临以下挑战: 找到所提供参数的最小公倍数,该公倍数可以被二者以及这些参数之间范围内的所有序列号平均除 范围将是两个数字的数组,不一定是数字顺序 例如,如果给定1和3,则找到1和3的最小公倍数,该公倍数也可以被1和3之间的所有数字整除。这里的答案是6 我在论坛上找到了一个非常简短的解决方案,但尽管我绞尽脑汁想了好几天,我还是不知道它是怎么回事。这是密码Javascript 需要了解此代码如何工作的帮助吗,javascript,Javascript,因此,freeCodeCamp面临以下挑战: 找到所提供参数的最小公倍数,该公倍数可以被二者以及这些参数之间范围内的所有序列号平均除 范围将是两个数字的数组,不一定是数字顺序 例如,如果给定1和3,则找到1和3的最小公倍数,该公倍数也可以被1和3之间的所有数字整除。这里的答案是6 我在论坛上找到了一个非常简短的解决方案,但尽管我绞尽脑汁想了好几天,我还是不知道它是怎么回事。这是密码 function smallestCommons(arr) { var max = Math
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;
}
有人能解释一下发生了什么事吗?它的简洁性很吸引人,但很想知道是怎么回事。基本上,代码接受一个变量multple(将其初始化为max)并检查multple是否是max和min之间所有值的倍数。如果是真的,则返回它。 否则,它将以multple(multple+=max)为单位递增max,并再次重复从i=max开始的步骤,并检查从max到min的所有值。 希望这有帮助。如果你还不明白,请告诉我 顺便说一句,我认为这段代码找到了介于max和min之间的所有值的一个公共倍数。它从max循环到min,并根据所有值检查multple 参见内联注释:
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;
}
因为我们试图找到一个公倍数,所以两个数中最小的公倍数可以是(但不一定)两个数中的较大数。因此,这就是我们开始测试的地方,即从两个中的较大数开始。 把这两个数字取为2和3。2的倍数是2,4,6,8。。。。以此类推,3的是3,6,9,12。。。。等等
在这里,普通倍数只能是更大数字ie 3的倍数。这就是为什么变量mltple每次递增一个更大的数字。接下来,我们将循环遍历所有数字,这些数字应根据要求划分mltple。一旦所有条件都满足,我们将返回答案。请阅读以了解为什么“向我解释此代码”问题是离题的,以及您可以做些什么使其成为主题。@JörgWMittag:注意。谢谢。:)非常感谢你!