因此freeCodeCamp面临挑战:
找到所提供参数的最小公倍数,这些参数可以被两者以及这些参数之间范围内的所有序号均分。
范围将是两个数字的数组,不一定按数字顺序。
例如,如果给定1和3,则求出1和3的最小公倍数,该公倍数也可以被1和3之间的所有数字整除。答案是6。 < / p>
我在论坛上找到了一个很短的解决方案,但是尽管花了我几天时间,但我仍无法弄清楚它是如何解决的。这是代码。
<tbody id="list">
<tr class='row'>
<td class='id'>b17dcat126</td>
<td class='name'>Nguyễn Nhật Minh</td>
<td class='phone'>010313234</td>
<td class='sex'>Nam</td>
<td>
<button class='btn btn-danger' onclick='deletefunc(15)' data-id='15'>Xoá</button>
<button class='btn btn-warning' data-toggle='modal' onclick='updatedata()' data-target='#update'>Sửa</button>
</td>
</tr>
</tbody>
有人可以解释正在发生的事情吗?它的简短性很吸引人,但是很想知道发生了什么。
答案 0 :(得分:1)
查看嵌入式注释:
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;
}
答案 1 :(得分:0)
基本上,代码接受一个变量multple(将其初始化为max),并检查multple是否为max和min之间所有值的倍数。如果为true,则将其返回。 否则,它将以最大倍数(multple + = max)递增max,并再次重复从i = max开始的步骤,并检查从max到min的所有值。 希望这可以帮助。让我知道您是否仍然不理解。
我认为这段代码正在找到介于max和min之间的所有值的公倍数。因为它从max一直循环到min,并针对所有值检查多个。
答案 2 :(得分:0)
由于我们试图找到一个公倍数,所以2个数的最低公倍数可能(但不一定)是两个数中的较大数。所以,那就是我们开始测试的地方。从两者中较大的一个开始。 取两个数字分别为2和3。2的倍数是2,4,6,8 ....,依此类推,而3的倍数是3,6,9,12 ....,依此类推。 在这里,公倍数只能是较大数字的倍数,即3。这就是为什么变量mltple每次都会增加较大数字的原因。接下来,我们遍历所有数字,这些数字应根据要求划分小数位数。一旦满足所有条件,我们将返回答案。