Skip to content

Commit 4c4e236

Browse files
committed
Added gcd function
1 parent 590d53b commit 4c4e236

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed

src/lib/math/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export * from './is-power-of-two/is-power-of-two';
22
export * from './nearest-highest-power-of-two/nearest-highest-power-of-two';
33
export * from './nearest-highest-power-of-two-result/nearest-highest-power-of-two-result';
44
export * from './greatest-common-divisor/greatest-common-divisor';
5+
export * from './least-common-multiple/least-common-multiple';
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// tslint:disable:no-expression-statement
2+
import test from 'ava';
3+
import { leastCommonMultiple } from './least-common-multiple';
4+
5+
test('finds LCM of positive numbers', t => {
6+
const tests = [
7+
[[4, 6], 12],
8+
[[334, 525252], 87717084],
9+
[[100000004, 244127], 1877900075116],
10+
[[1000000001, 513], 27000000027]
11+
];
12+
for (const vtest of tests) {
13+
const [v, a] = vtest;
14+
// @ts-ignore
15+
t.is(leastCommonMultiple(...v), a);
16+
}
17+
});
18+
19+
test('finds LCM of negative numbers', t => {
20+
const tests = [
21+
[[-4, -6], 12],
22+
[[-334, 525252], 87717084],
23+
[[-100000004, 244127], 1877900075116],
24+
[[1000000001, -513], 27000000027]
25+
];
26+
for (const vtest of tests) {
27+
const [v, a] = vtest;
28+
// @ts-ignore
29+
t.is(leastCommonMultiple(...v), a);
30+
}
31+
});
32+
33+
test('finds LCM of 1 and 1', t => {
34+
t.is(leastCommonMultiple(1, 1), 1);
35+
});
36+
37+
test('works LCM with zero values', t => {
38+
t.is(leastCommonMultiple(0, 0), 0);
39+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { greatestCommonDivisor } from '..';
2+
3+
/**
4+
* Returns least common multiple of two numbers using GCD
5+
*
6+
* @link https://en.wikipedia.org/wiki/Least_common_multiple#Using_the_greatest_common_divisor
7+
*
8+
* @param {number} a
9+
* @param {number} b
10+
* @returns {number}
11+
*/
12+
export function leastCommonMultiple(a: number, b: number): number {
13+
return Math.abs(a * b) / greatestCommonDivisor(a, b);
14+
}

0 commit comments

Comments
 (0)