From 318ef2e6c2003f36085e370e587bb358aa9c4bc6 Mon Sep 17 00:00:00 2001 From: patrickwestervelt Date: Mon, 17 Oct 2022 10:23:03 -0400 Subject: [PATCH] Feat: Added GCF --- Maths/GreatestCommonFactor.ts | 29 +++++++++++++++++++ Maths/test/GreatestCommonFactor.test.ts | 37 +++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 Maths/GreatestCommonFactor.ts create mode 100644 Maths/test/GreatestCommonFactor.test.ts diff --git a/Maths/GreatestCommonFactor.ts b/Maths/GreatestCommonFactor.ts new file mode 100644 index 00000000..15383e62 --- /dev/null +++ b/Maths/GreatestCommonFactor.ts @@ -0,0 +1,29 @@ +/** + * @function GreatestCommonFactor + * @description Determine the greatest common factor of a group of numbers. + * @param {Number[]} nums - An array of numbers. + * @return {Number} - The greatest common factor. + * @see https://www.mathsisfun.com/greatest-common-factor.html + * @example GreatestCommonFactor(12, 8) = 4 + * @example GreatestCommonFactor(3, 6) = 3 + * @example GreatestCommonFactor(32, 16, 12) = 4 + */ + +export const binaryGCF = (a: number, b: number): number => { + if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) { + throw new Error("numbers must be natural to determine factors"); + } + + while (b) { + [a, b] = [b, a % b] + } + return a; +} + +export const greatestCommonFactor = (nums: number[]): number => { + if (nums.length === 0) { + throw new Error("at least one number must be passed in"); + } + + return nums.reduce(binaryGCF); +}; \ No newline at end of file diff --git a/Maths/test/GreatestCommonFactor.test.ts b/Maths/test/GreatestCommonFactor.test.ts new file mode 100644 index 00000000..f5bd6852 --- /dev/null +++ b/Maths/test/GreatestCommonFactor.test.ts @@ -0,0 +1,37 @@ +import { binaryGCF, greatestCommonFactor } from "../GreatestCommonFactor"; + +describe("binaryGCF", () => { + test.each([[12, 8, 4], [1, 199, 1], [88, 40, 8], [288, 160, 32]])( + "of given two numbers is correct", + (numa, numb, expected) => { + expect(binaryGCF(numa, numb)).toBe(expected); + }, + ); + + test("only whole numbers should be accepted", () => { + expect(() => binaryGCF(0.5, 0.8)).toThrowError( + "numbers must be natural to determine factors", + ); + }); + + test("only positive numbers should be accepted", () => { + expect(() => binaryGCF(-2, 4)).toThrowError( + "numbers must be natural to determine factors", + ); + }); +}); + +describe("greatestCommonFactor", () => { + test.each([[[7], 7], [[12, 8], 4], [[1, 199], 1], [[88, 40, 32], 8], [[288, 160, 64], 32]])( + "of given list is correct", + (nums, expected) => { + expect(greatestCommonFactor(nums)).toBe(expected); + }, + ); + + test("the list should consist of at least one number", () => { + expect(() => greatestCommonFactor([])).toThrowError( + "at least one number must be passed in", + ); + }); +}); \ No newline at end of file