Skip to content

Commit ad57449

Browse files
T1LTappgurueu
andauthored
feat(maths): added IsPrime (TheAlgorithms#102)
* feat(maths): added IsPrime * Fix `IsPrime` for perfect squares * Add perfect square to the tests --------- Co-authored-by: Lars Müller <[email protected]>
1 parent 54d6e97 commit ad57449

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

maths/is_prime.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @function IsPrime
3+
* @description Determine if given number is prime.
4+
* @param {number} num - A natural number.
5+
* @return {boolean} - Whether the given number is prime.
6+
* @see https://en.wikipedia.org/wiki/Prime_number
7+
* @example IsPrime(2) = false
8+
* @example IsPrime(3) = true
9+
*/
10+
11+
export const IsPrime = (num: number): boolean => {
12+
// raise corresponding errors upon invalid inputs
13+
if (num <= 0 || !Number.isInteger(num)) {
14+
throw new Error("only natural numbers are supported");
15+
}
16+
17+
// handle input being 1
18+
if (num === 1) return false;
19+
20+
// iterate from 2 to the square root of num to find a factor
21+
// return false upon finding a factor
22+
for (let i = 2; i <= Math.sqrt(num); i++) {
23+
if (num % i === 0) return false;
24+
}
25+
26+
// if the entire loop runs without finding a factor, return true
27+
return true;
28+
};

maths/test/is_prime.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { IsPrime } from "../is_prime";
2+
3+
describe("IsPrime", () => {
4+
test.each([[1, false], [2, true], [3, true], [3*3, false], [13, true], [24, false]])(
5+
"correct output for %i",
6+
(nums, expected) => {
7+
expect(IsPrime(nums)).toBe(expected);
8+
},
9+
);
10+
11+
test.each([-890, -5.56, -7, 0.73, 4.2, NaN, -Infinity, Infinity])(
12+
"should throw an error for non natural number %d",
13+
(num) => {
14+
expect(() => IsPrime(num)).toThrowError(
15+
"only natural numbers are supported",
16+
);
17+
},
18+
);
19+
});

0 commit comments

Comments
 (0)