From 074131e4c76d9bebbe509510821272909e23f9a6 Mon Sep 17 00:00:00 2001 From: sarthakgupta1907-cell Date: Tue, 3 Nov 2026 10:20:55 +0530 Subject: [PATCH] feat: add isPrime algorithm --- Maths/IsPrime.js | 25 ++++++++++++++++++++ Maths/test/IsPrime.test.js | 47 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 Maths/IsPrime.js create mode 100644 Maths/test/IsPrime.test.js diff --git a/Maths/IsPrime.js b/Maths/IsPrime.js new file mode 100644 index 0000000000..469c38099e --- /dev/null +++ b/Maths/IsPrime.js @@ -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 } diff --git a/Maths/test/IsPrime.test.js b/Maths/test/IsPrime.test.js new file mode 100644 index 0000000000..b52ba921a0 --- /dev/null +++ b/Maths/test/IsPrime.test.js @@ -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) + }) +})