javascript 学习用ES6求最小公倍数

9udxz4iz  于 2023-01-04  发布在  Java
关注(0)|答案(1)|浏览(100)

我写的代码在一个更高的范围内超时。任何通过使用高阶ES6函数来优化代码的方法。
在线环境的链接:https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple

function smallestCommons(arr) {
  // Return the Smallest Common Multiple for pair of Input Numbers.
  
  const [min, max] = arr.sort((a,b)=>a-b); 
  // Sorting Input Array to give min and max values for the range

  const range = Array(max-min+1).fill(0).map((_,i)=>i+min);
  // Initialize the Array

  let prodAll = range.reduce((product,number)=>product*number);
  // Finding the product of all numbers which is a gauranteed multiple of the range

  let res = Array(prodAll/max).fill(0).map((_,i)=>(i+1)*max) // Initialize an Array of all the multiples of the 'max' number upto 'prodAll'
                            .find(mulp=>range.every((val)=>mulp%val===0)); // check if any number meets the divisiblable criteria sooner then 'prodAll'
        

  return res;
}

console.log(
  smallestCommons([1,13])
)
lbsnaicq

lbsnaicq1#

试试这个:

function smallestCommons(arr) {
  // Return the Smallest Common Multiple for pair of Input Numbers.
  
  const [min, max] = arr.sort((a,b)=>a-b); 
  // Sorting Input Array to give min and max values for the range

  const range = Array(max-min+1).fill(0).map((_,i)=>i+min);
  // Initialize the Array

  let res = range.reduce((lcm, number) => {
    // Calculate the least common multiple using the current value and the previously calculated lcm
    return (lcm * number) / gcd(lcm, number);
  }, max);

  return res;
}

function gcd(a, b) {
  if (b === 0) {
    return a;
  }
  return gcd(b, a % b);
}

smallestCommons([1, 4]);

此版本使用reduce函数来迭代范围,并使用当前值和以前计算的lcm来计算最小公倍数。它还使用分离函数(gcd)来使用Euclid算法计算最大公约数,这更高效。

相关问题