| 68 | * @example isPrime(3) = true |
| 69 | */ |
| 70 | export 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 | } |