Smallest Common Multiple
Find the smallest common multiple of the provided parameters that can be evenly divided by both, as well as by all sequential numbers in the range between these parameters.
The range will be an array of two numbers that will not necessarily be in numerical order.
For example, if given 1 and 3, find the smallest common multiple of both 1 and 3 that is also evenly divisible by all numbers between 1 and 3. The answer here would be 6.
使用sort取两个数的最大值最小值
const [min,max] = arr.sort((a,b)=>a-b)
使用fill或者from生成一个[min,max]范围数组
fill+map
https://devdocs.io/javascript/global_objects/array/fill
const [min, max] = arr.sort((a, b) => a - b)
console.log(min, max)
console.log(Array(max - min + 1)
.fill(0)
.map((_, i) => i + min))
from
from的第二个参数可以是一个函数用来处理每一项的值
https://devdocs.io/javascript/global_objects/array/from
console.log(Array.from({ length: max - min + 1 }, (_, i) => min + i))
for循环之前 求出最大临界值
然后对范维数组每一项求整除
function smallestCommons(arr) {
const [min, max] = arr.sort((a, b) => a - b)
console.log(min, max)
const range = Array.from({ length: max - min + 1 }, (_, i) => min + i)
const upperBound = range.reduce((prev, cur) => prev * cur)
for (let multiple = max; multiple < upperBound; multiple += max) {
const devisible = range.every(v => multiple % v === 0)
if (devisible) {
console.log(multiple)
return multiple
}
}
}
console.log(
smallestCommons([1, 5])
)