MCPcopy Create free account
hub / github.com/TheAlgorithms/TypeScript / isPrime

Function isPrime

maths/primes.ts:70–87  ·  view source on GitHub ↗
(num: number)

Source from the content-addressed store, hash-verified

68 * @example isPrime(3) = true
69 */
70export const isPrime = (num: number): boolean => {
71 // raise corresponding errors upon invalid inputs
72 if (num <= 0 || !Number.isInteger(num)) {
73 throw new Error('only natural numbers are supported')
74 }
75
76 // handle input being 1
77 if (num === 1) return false
78
79 // iterate from 2 to the square root of num to find a factor
80 // return false upon finding a factor
81 for (let i = 2; i <= Math.sqrt(num); i++) {
82 if (num % i === 0) return false
83 }
84
85 // if the entire loop runs without finding a factor, return true
86 return true
87}

Callers 1

primes.test.tsFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected