Skip to content

Commit 074131e

Browse files
feat: add isPrime algorithm
1 parent 5c39e87 commit 074131e

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎Maths/IsPrime.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function isPrime
3+
* @description A prime number is a natural number greater than 1 that has
4+
* no positive divisors other than 1 and itself. This function checks
5+
* whether a given number is prime.
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is prime, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Prime_number
9+
* @example isPrime(2) => true
10+
* @example isPrime(11) => true
11+
* @example isPrime(4) => false
12+
*/
13+
const isPrime = (n) => {
14+
if (!Number.isInteger(n) || n < 2) {
15+
throw new TypeError('Input must be an integer greater than or equal to 2')
16+
}
17+
if (n === 2) return true
18+
if (n % 2 === 0) return false
19+
for (let i = 3; i <= Math.sqrt(n); i += 2) {
20+
if (n % i === 0) return false
21+
}
22+
return true
23+
}
24+
25+
export { isPrime }

‎Maths/test/IsPrime.test.js‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import { isPrime } from '../IsPrime.js'
2+
3+
describe('isPrime', () => {
4+
test('2 is prime', () => {
5+
expect(isPrime(2)).toBe(true)
6+
})
7+
8+
test('3 is prime', () => {
9+
expect(isPrime(3)).toBe(true)
10+
})
11+
12+
test('4 is NOT prime', () => {
13+
expect(isPrime(4)).toBe(false)
14+
})
15+
16+
test('11 is prime', () => {
17+
expect(isPrime(11)).toBe(true)
18+
})
19+
20+
test('13 is prime', () => {
21+
expect(isPrime(13)).toBe(true)
22+
})
23+
24+
test('25 is NOT prime', () => {
25+
expect(isPrime(25)).toBe(false)
26+
})
27+
28+
test('97 is prime', () => {
29+
expect(isPrime(97)).toBe(true)
30+
})
31+
32+
test('100 is NOT prime', () => {
33+
expect(isPrime(100)).toBe(false)
34+
})
35+
36+
test('throws TypeError for 1', () => {
37+
expect(() => isPrime(1)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for negative input', () => {
41+
expect(() => isPrime(-7)).toThrow(TypeError)
42+
})
43+
44+
test('throws TypeError for float input', () => {
45+
expect(() => isPrime(2.5)).toThrow(TypeError)
46+
})
47+
})

0 commit comments

Comments
 (0)