Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: trekhleb/javascript-algorithms
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: master
Choose a base ref
...
head repository: Madapati-Brungeshwar/javascript-algorithms
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
Able to merge. These branches can be automatically merged.
  • 1 commit
  • 2 files changed
  • 1 contributor

Commits on Aug 15, 2024

  1. Copy the full SHA
    a4dd3bd View commit details
Showing with 42 additions and 0 deletions.
  1. +26 −0 src/algorithms/math/lcm-array/_test_/lcm-array.test.js
  2. +16 −0 src/algorithms/math/lcm-array/lcm-array.js
26 changes: 26 additions & 0 deletions src/algorithms/math/lcm-array/_test_/lcm-array.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import leastCommonMultipleArray from '../lcm-array.js';

describe('leastCommonMultiple', () => {
it('should find least common multiple', () => {
expect(() => leastCommonMultipleArray([])).toThrow(Error('Array is empty'));
expect(leastCommonMultipleArray([0, 0])).toBe(0);
expect(leastCommonMultipleArray([1, 0])).toBe(0);
expect(leastCommonMultipleArray([0, 1])).toBe(0);
expect(leastCommonMultipleArray([4, 6])).toBe(12);
expect(leastCommonMultipleArray([6, 21])).toBe(42);
expect(leastCommonMultipleArray([7, 2])).toBe(14);
expect(leastCommonMultipleArray([3, 5])).toBe(15);
expect(leastCommonMultipleArray([7, 3])).toBe(21);
expect(leastCommonMultipleArray([1000000, 2])).toBe(1000000);
expect(leastCommonMultipleArray([-9, -18])).toBe(18);
expect(leastCommonMultipleArray([-7, -9])).toBe(63);
expect(leastCommonMultipleArray([-7, 9])).toBe(63);
expect(leastCommonMultipleArray([2, 3, 5])).toBe(30);
expect(leastCommonMultipleArray([2, 4, 5])).toBe(20);
expect(leastCommonMultipleArray([2, 4, 6, 8])).toBe(24);
expect(leastCommonMultipleArray([2, 4, 6, 7, 8])).toBe(168);
expect(leastCommonMultipleArray([2, 3, 5, 7, 11, 13, 17, 19])).toBe(
9699690
);
});
});
16 changes: 16 additions & 0 deletions src/algorithms/math/lcm-array/lcm-array.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import euclideanAlgorithm from '../euclidean-algorithm/euclideanAlgorithm.js';

export default function leastCommonMultipleArray(arr) {
let siz = arr.length;
if (siz == 0) throw new Error('Array is empty');
for (let num of arr) {
if (num == 0) return 0;
}
let lcm = arr[0];
for (let i = 0; i < siz; i++) {
let prod = Math.abs(lcm * arr[i]);
let gcd = euclideanAlgorithm(lcm, arr[i]);
lcm = prod / gcd;
}
return lcm;
}