https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple


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取两个数的最大值最小值

  1. const [min,max] = arr.sort((a,b)=>a-b)

使用fill或者from生成一个[min,max]范围数组

fill+map

https://devdocs.io/javascript/global_objects/array/fill

  1. const [min, max] = arr.sort((a, b) => a - b)
  2. console.log(min, max)
  3. console.log(Array(max - min + 1)
  4. .fill(0)
  5. .map((_, i) => i + min))

from

from的第二个参数可以是一个函数用来处理每一项的值

https://devdocs.io/javascript/global_objects/array/from

  1. console.log(Array.from({ length: max - min + 1 }, (_, i) => min + i))

for循环之前 求出最大临界值

然后对范维数组每一项求整除

  1. function smallestCommons(arr) {
  2. const [min, max] = arr.sort((a, b) => a - b)
  3. console.log(min, max)
  4. const range = Array.from({ length: max - min + 1 }, (_, i) => min + i)
  5. const upperBound = range.reduce((prev, cur) => prev * cur)
  6. for (let multiple = max; multiple < upperBound; multiple += max) {
  7. const devisible = range.every(v => multiple % v === 0)
  8. if (devisible) {
  9. console.log(multiple)
  10. return multiple
  11. }
  12. }
  13. }
  14. console.log(
  15. smallestCommons([1, 5])
  16. )