Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 8afe254

Browse files
authoredNov 6, 2024
Update leastCommonMultiple.js
applied the reduce method to iteratively compute the LCM across all numbers in the array, combining each pair of results. Additionally, I used the Euclidean algorithm for GCD calculation, which optimizes the LCM computation by reducing the multiplication size
1 parent ca3d16d commit 8afe254

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed
 
Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm';
22

33
/**
4-
* @param {number} a
5-
* @param {number} b
6-
* @return {number}
4+
* Finds the LCM of an array of numbers.
5+
* @param {number[]} arr - Array of numbers
6+
* @return {number} - LCM of the entire array
77
*/
8+
export default function leastCommonMultipleArray(arr) {
9+
if (arr.length === 0) return 0;
810

9-
export default function leastCommonMultiple(a, b) {
10-
return ((a === 0) || (b === 0)) ? 0 : Math.abs(a * b) / euclideanAlgorithm(a, b);
11+
return arr.reduce((lcm, num) => leastCommonMultiple(lcm, num), 1);
1112
}

0 commit comments

Comments
 (0)
Please sign in to comment.