Skip to content

Commit 77334fc

Browse files
zFl4wlessT1LT
andauthored
feat(maths): finishes Factors (#112)
* feat(maths): added Factors * fix: fixed test cases for Factors * fix(maths): renamed Factors to FindFactors and minor optimizations * fix(maths): fixed square root bug * feat: improvements & resolves requested changes * fix: removes not needed check * improvement: replaces while with for loop --------- Co-authored-by: Nishant Racherla <[email protected]>
1 parent 4c5469f commit 77334fc

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

maths/factors.ts

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @function FindFactors
3+
* @description Find all the factors of a natural number.
4+
* @param {number} num - A natural number.
5+
* @return {Set<number>} - A set of all the factors of given natural number.
6+
* @see https://en.wikipedia.org/wiki/Divisor
7+
* @example FindFactors(1) = [1]
8+
* @example FindFactors(4) = [1,2,4]
9+
* @example FindFactors(16) = [1,3,5,15]
10+
*/
11+
export const FindFactors = (num: number): Set<number> => {
12+
if (num <= 0 || !Number.isInteger(num)) {
13+
throw new Error("Only natural numbers are supported.");
14+
}
15+
16+
const res: Set<number> = new Set();
17+
// Iterates from 1 to square root of num & pushes factors into the res set.
18+
for (let i = 1; i * i <= num; i++) {
19+
if (num % i === 0) {
20+
res.add(i);
21+
22+
const sqrtFactor = Math.floor(num / i);
23+
res.add(sqrtFactor);
24+
}
25+
}
26+
27+
return res;
28+
};

maths/test/factors.test.ts

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { FindFactors } from "../factors";
2+
3+
describe("FindFactors", () => {
4+
test.each([-890, -5.56, -7, 0, 0.73, 4.2, NaN, -Infinity, Infinity])(
5+
"should throw an error for non natural number %d",
6+
(num) => {
7+
expect(() => FindFactors(num)).toThrowError(
8+
"Only natural numbers are supported."
9+
);
10+
}
11+
);
12+
13+
test.each([
14+
[1, new Set([1])],
15+
[2, new Set([1, 2])],
16+
[4, new Set([1, 2, 4])],
17+
[6, new Set([1, 2, 3, 6])],
18+
[16, new Set([1, 2, 4, 8, 16])],
19+
])(
20+
"of %i should return the correct set of its factors",
21+
(num, expected) => {
22+
expect(FindFactors(num)).toStrictEqual(expected);
23+
}
24+
);
25+
});

0 commit comments

Comments
 (0)