Skip to content
Open
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
25 changes: 25 additions & 0 deletions Maths/IsPrime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* @function isPrime
* @description A prime number is a natural number greater than 1 that has
* no positive divisors other than 1 and itself. This function checks
* whether a given number is prime.
* @param {number} n - A positive integer
* @returns {boolean} - True if n is prime, false otherwise
* @see https://en.wikipedia.org/wiki/Prime_number
* @example isPrime(2) => true
* @example isPrime(11) => true
* @example isPrime(4) => false
*/
const isPrime = (n) => {
if (!Number.isInteger(n) || n < 2) {
throw new TypeError('Input must be an integer greater than or equal to 2')
}
if (n === 2) return true
if (n % 2 === 0) return false
for (let i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i === 0) return false
}
return true
}

export { isPrime }
47 changes: 47 additions & 0 deletions Maths/test/IsPrime.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { isPrime } from '../IsPrime.js'

describe('isPrime', () => {
test('2 is prime', () => {
expect(isPrime(2)).toBe(true)
})

test('3 is prime', () => {
expect(isPrime(3)).toBe(true)
})

test('4 is NOT prime', () => {
expect(isPrime(4)).toBe(false)
})

test('11 is prime', () => {
expect(isPrime(11)).toBe(true)
})

test('13 is prime', () => {
expect(isPrime(13)).toBe(true)
})

test('25 is NOT prime', () => {
expect(isPrime(25)).toBe(false)
})

test('97 is prime', () => {
expect(isPrime(97)).toBe(true)
})

test('100 is NOT prime', () => {
expect(isPrime(100)).toBe(false)
})

test('throws TypeError for 1', () => {
expect(() => isPrime(1)).toThrow(TypeError)
})

test('throws TypeError for negative input', () => {
expect(() => isPrime(-7)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => isPrime(2.5)).toThrow(TypeError)
})
})
Loading