GeezerVison is showing github.com — solution: ProjectEuler-007 (#1142) · Algorithms-Learn/JavaScript@d0e61e1
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +27Lines changed: 27 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +import { PrimeCheck } from '../Maths/PrimeCheck.js' |
| 2 | + |
| 3 | +/** |
| 4 | + * Find nth Prime Number |
| 5 | + * |
| 6 | + * P.S.(Project Euler - 007): |
| 7 | + * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. |
| 8 | + * What is the 10001st prime number? |
| 9 | + * |
| 10 | + * @param {Number} n |
| 11 | + * @returns {Number} returns the nth prime number |
| 12 | + */ |
| 13 | +export const nthPrime = (n) => { |
| 14 | + if (n < 1) { |
| 15 | + throw new Error('Invalid Input') |
| 16 | + } |
| 17 | + |
| 18 | + let count = 0 |
| 19 | + let candidateValue = 1 |
| 20 | + while (count < n) { |
| 21 | + candidateValue++ |
| 22 | + if (PrimeCheck(candidateValue)) { |
| 23 | + count++ |
| 24 | + } |
| 25 | + } |
| 26 | + return candidateValue |
| 27 | +} |
Collapse file
Copy file name to clipboard +17Lines changed: 17 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +import { nthPrime } from '../Problem007.js' |
| 2 | + |
| 3 | +describe('checking nth prime number', () => { |
| 4 | + it('should be invalid input if number is negative', () => { |
| 5 | + expect(() => nthPrime(-3)).toThrowError('Invalid Input') |
| 6 | + }) |
| 7 | + it('should be invalid input if number is 0', () => { |
| 8 | + expect(() => nthPrime(0)).toThrowError('Invalid Input') |
| 9 | + }) |
| 10 | + test('if the number is greater than 0', () => { |
| 11 | + expect(nthPrime(10)).toBe(29) |
| 12 | + }) |
| 13 | + // Project Euler Condition Check |
| 14 | + test('if the number is 10001', () => { |
| 15 | + expect(nthPrime(10001)).toBe(104743) |
| 16 | + }) |
| 17 | +}) |