Skip to content

Commit 07b1404

Browse files
authored
Feat: Added GCF (#63)
1 parent cd08a00 commit 07b1404

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

Maths/GreatestCommonFactor.ts

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @function GreatestCommonFactor
3+
* @description Determine the greatest common factor of a group of numbers.
4+
* @param {Number[]} nums - An array of numbers.
5+
* @return {Number} - The greatest common factor.
6+
* @see https://www.mathsisfun.com/greatest-common-factor.html
7+
* @example GreatestCommonFactor(12, 8) = 4
8+
* @example GreatestCommonFactor(3, 6) = 3
9+
* @example GreatestCommonFactor(32, 16, 12) = 4
10+
*/
11+
12+
export const binaryGCF = (a: number, b: number): number => {
13+
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) {
14+
throw new Error("numbers must be natural to determine factors");
15+
}
16+
17+
while (b) {
18+
[a, b] = [b, a % b]
19+
}
20+
return a;
21+
}
22+
23+
export const greatestCommonFactor = (nums: number[]): number => {
24+
if (nums.length === 0) {
25+
throw new Error("at least one number must be passed in");
26+
}
27+
28+
return nums.reduce(binaryGCF);
29+
};
+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { binaryGCF, greatestCommonFactor } from "../GreatestCommonFactor";
2+
3+
describe("binaryGCF", () => {
4+
test.each([[12, 8, 4], [1, 199, 1], [88, 40, 8], [288, 160, 32]])(
5+
"of given two numbers is correct",
6+
(numa, numb, expected) => {
7+
expect(binaryGCF(numa, numb)).toBe(expected);
8+
},
9+
);
10+
11+
test("only whole numbers should be accepted", () => {
12+
expect(() => binaryGCF(0.5, 0.8)).toThrowError(
13+
"numbers must be natural to determine factors",
14+
);
15+
});
16+
17+
test("only positive numbers should be accepted", () => {
18+
expect(() => binaryGCF(-2, 4)).toThrowError(
19+
"numbers must be natural to determine factors",
20+
);
21+
});
22+
});
23+
24+
describe("greatestCommonFactor", () => {
25+
test.each([[[7], 7], [[12, 8], 4], [[1, 199], 1], [[88, 40, 32], 8], [[288, 160, 64], 32]])(
26+
"of given list is correct",
27+
(nums, expected) => {
28+
expect(greatestCommonFactor(nums)).toBe(expected);
29+
},
30+
);
31+
32+
test("the list should consist of at least one number", () => {
33+
expect(() => greatestCommonFactor([])).toThrowError(
34+
"at least one number must be passed in",
35+
);
36+
});
37+
});

0 commit comments

Comments
 (0)