Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

algorithm: greatest common factor #63

Merged
merged 1 commit into from
Oct 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Maths/GreatestCommonFactor.ts
Original file line number Diff line number Diff line change
@@ -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);
};
37 changes: 37 additions & 0 deletions Maths/test/GreatestCommonFactor.test.ts
Original file line number Diff line number Diff line change
@@ -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",
);
});
});