| 3 | 3 | // convenience to get you started writing code faster. |
| 4 | 4 | // |
| 5 | 5 | |
| 6 | export const prime = () => { | |
| 7 | throw new Error('Remove this line and implement the function'); | |
| 6 | export const prime = (n) => { | |
| 7 | // Edge Case: n is not a positive integer | |
| 8 | if (!Number.isInteger(n) || n <= 0) { | |
| 9 | throw new Error('there is no zeroth prime'); | |
| 10 | } | |
| 11 | ||
| 12 | // Edge Case: n is 1 | |
| 13 | if (n === 1) { | |
| 14 | return 2; | |
| 15 | } | |
| 16 | ||
| 17 | const primes = [2]; | |
| 18 | let candidate = 3; | |
| 19 | ||
| 20 | while (primes.length < n) { | |
| 21 | let isPrime = true; | |
| 22 | ||
| 23 | // Check if candidate is divisible by any previously found prime | |
| 24 | for (const p of primes) { | |
| 25 | // Edge Case: integer overflow - we only need to check up to sqrt(candidate) | |
| 26 | if (p * p > candidate) { | |
| 27 | break; | |
| 28 | } | |
| 29 | ||
| 30 | if (candidate % p === 0) { | |
| 31 | isPrime = false; | |
| 32 | break; | |
| 33 | } | |
| 34 | } | |
| 35 | ||
| 36 | if (isPrime) { | |
| 37 | primes.push(candidate); | |
| 38 | } | |
| 39 | ||
| 40 | // Only check odd numbers after 2 | |
| 41 | candidate += 2; | |
| 42 | } | |
| 43 | ||
| 44 | return primes[n - 1]; | |
| 8 | 45 | }; |
| 46 | ||
| 47 | // Handled Edge Cases: n <= 0, n = 1, non-integer inputs, integer overflow |