在 JavaScript 中計算多個數字的最小公倍數
我們需要編寫一個 JavaScript 函式,該函式接受任意長度的數字陣列並返回它們的最小公倍數。
我們將分多個部分解決此問題 −
部分 1 − 我們將建立一個幫助函式來計算兩個數字的最大公約數 (GCD)
部分 2 − 然後使用部分 1 中的幫助函式,我們將建立另一個幫助函式來計算兩個數字的最小公倍數 (LCM)。
部分 3 − 最後,使用部分 2 中的幫助函式,我們將建立一個函式,該函式遍歷陣列並計算陣列最小公倍數。
示例
程式碼如下 −
const calculateLCM = (...arr) => { const gcd2 = (a, b) => { // Greatest common divisor of 2 integers if(!b) return b===0 ? a : NaN; return gcd2(b, a%b); }; const lcm2 = (a, b) => { // Least common multiple of 2 integers return a * b / gcd2(a, b); } // Least common multiple of a list of integers let n = 1; for(let i = 0; i < arr.length; ++i){ n = lcm2(arr[i], n); } return n; }; console.log(calculateLCM(12, 18, 7, 15, 20, 24, 28));
輸出
控制檯中的輸出如下 −
2520
廣告