Skip to content

feat(maths): added Factors #103

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

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
24 changes: 24 additions & 0 deletions maths/factors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @function Factors
* @description Find all the factors of a natural number.
* @param {number} num - A natural number.
* @return {number[]} - An array of all the factors of given natural number.
* @see https://en.wikipedia.org/wiki/Divisor
* @example Factors(1) = [1]
* @example Factors(4) = [1,2,4]
* @example Factors(16) = [1,3,5,15]
*/

export const Factors = (num: number): number[] => {
if (num <= 0 || !Number.isInteger(num)) {
throw new Error("only natural numbers are supported");
}

const res: number[] = [];
// iterate from 1 to num and push factors into the res array
for (let i: number = 0; i <= num; i++) {
if (num % i === 0) res.push(i);
}

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

describe("Factors", () => {
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(() => Factors(num)).toThrowError(
"only natural numbers are supported",
);
},
);

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