Skip to content

feat(maths): finishes Factors #112

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

Merged
merged 7 commits into from
Mar 12, 2023
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
28 changes: 28 additions & 0 deletions maths/factors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @function FindFactors
* @description Find all the factors of a natural number.
* @param {number} num - A natural number.
* @return {Set<number>} - A set of all the factors of given natural number.
* @see https://en.wikipedia.org/wiki/Divisor
* @example FindFactors(1) = [1]
* @example FindFactors(4) = [1,2,4]
* @example FindFactors(16) = [1,3,5,15]
*/
export const FindFactors = (num: number): Set<number> => {
if (num <= 0 || !Number.isInteger(num)) {
throw new Error("Only natural numbers are supported.");
}

const res: Set<number> = new Set();
// Iterates from 1 to square root of num & pushes factors into the res set.
for (let i = 1; i * i <= num; i++) {
if (num % i === 0) {
res.add(i);

const sqrtFactor = Math.floor(num / i);
res.add(sqrtFactor);
}
}

return res;
};
25 changes: 25 additions & 0 deletions maths/test/factors.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { FindFactors } from "../factors";

describe("FindFactors", () => {
test.each([-890, -5.56, -7, 0, 0.73, 4.2, NaN, -Infinity, Infinity])(
"should throw an error for non natural number %d",
(num) => {
expect(() => FindFactors(num)).toThrowError(
"Only natural numbers are supported."
);
}
);

test.each([
[1, new Set([1])],
[2, new Set([1, 2])],
[4, new Set([1, 2, 4])],
[6, new Set([1, 2, 3, 6])],
[16, new Set([1, 2, 4, 8, 16])],
])(
"of %i should return the correct set of its factors",
(num, expected) => {
expect(FindFactors(num)).toStrictEqual(expected);
}
);
});