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 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
34 changes: 34 additions & 0 deletions maths/factors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* @function FindFactors
* @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 FindFactors(1) = [1]
* @example FindFactors(4) = [1,2,4]
* @example FindFactors(16) = [1,3,5,15]
*/

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

const res: number[] = [];
// iterate from 1 to square root of num
// push factors into the res array
let i: number = 1;
while (i * i <= num) {
if (num % i === 0) {
res.push(i);
// if i is the same as num / i
const sqrtFactor = Math.floor(num / i);
if (sqrtFactor !== i) {
res.push(sqrtFactor);
}
}
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 { 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, [1]], [2, [1,2]], [4, [1,4,2]], [6, [1,6,2,3]], [16, [1,16,2,8,4]]])(
"of %i should return the correct array of its factors",
(num, expected) => {
expect(FindFactors(num)).toStrictEqual(expected);
},
);
});