【问题标题】:Smallest Common Multiple: Intermediate Javascript Algorithm最小公倍数:中级 Javascript 算法
【发布时间】:2020-09-05 16:48:16
【问题描述】:

问题

找到所提供参数的最小公倍数,该公倍数可以被两者以及这些参数之间范围内的所有序号均分。

范围将是一个由两个数字组成的数组,不一定按数字顺序。

例如,如果给定 1 和 3,请找出 1 和 3 的最小公倍数,它也能被 1 和 3 之间的所有数字整除。这里的答案是 6。

到目前为止我的代码

function smallestCommons(arr) {
  
  let newArr = [];
  
  let changedArr = arr.sort((a, b)=>{
   
    if(a>b){
      return 1;
    }
   
    if(b>a){
      return -1;
    } else {
      return 0;
    }
  })

  for(let i = changedArr[0]; i < changedArr[1]; i++){
    newArr.push(i);
  }

let answer = changedArr.every((item)=>{
  
})

}


smallestCommons([1,5]);

我的问题

  1. 我希望您能够帮助我理解这个问题 - 我已经研究了最小公倍数,但“可整除”让我很反感。
  2. 我希望您能解决问题,并简单地分解解决方案。

我问了很多,所以如果你回答,非常感谢!

【问题讨论】:

  • 请注意,lcm 操作是可交换的和关联的。然后例如你有 lcm(a, b, c) = lcm (lcm(a, b), c) = lcm (a, lcm (b, c))。如果您能够计算两个操作数的 lcm,那么您可以对任意数量的操作数进行迭代。

标签: javascript algorithm


【解决方案1】:

// since the number is evenly divided by all numbers from min to max
// it is the least common multiple of all numbers in the array [min, min + 1, min + 2, ... max]
const smallestCommonMultiple = (a, b) => {
	const [min, max] = [Math.min(a, b), Math.max(a, b)];
	// create the array from min to max
	const range = [...Array(max - min + 1)].map((_, k) => min + k);
	// greatest common divisor of two numbers
	const gcd = (a, b) => b ? gcd(b, a % b) : Math.abs(a);
	// least common multiple of two numbers
	const lcm = (a, b) => a * b / gcd(a, b);
	// least common multiple of an array of numbers
	const lcma = array => array.reduce(lcm);
	return lcma(range);
}
console.log(smallestCommonMultiple(1, 3));
console.log(smallestCommonMultiple(2, 4));
console.log(smallestCommonMultiple(3, 5));

【讨论】:

    猜你喜欢
    • 2020-10-12
    • 1970-01-01
    • 2011-05-12
    • 2020-07-11
    • 1970-01-01
    • 2022-11-27
    • 2021-07-16
    • 1970-01-01
    相关资源
    最近更新 更多