簡體   English   中英

學習使用 ES6 求最小公倍數

[英]Learning to find the Smallest Common Multiple Using ES6

我寫的代碼在更高的范圍內超時。 任何通過使用高階 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)=>ab); // 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]) )

試試這個:

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 function 遍歷范圍並使用當前值和先前計算的 lcm 計算最小公倍數。 它還使用分離的 function ( gcd ) 使用歐幾里德算法計算最大公約數,效率更高。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM