-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP7.js
62 lines (48 loc) · 1.24 KB
/
P7.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/* ====== Problem 7 =================================== *
*
* By listing the first six prime numbers:
*
* 2, 3, 5, 7, 11, and 13,
*
* We can see that the 6th prime is 13.
*
* What is the 10,001st prime number?
*
* ========================================**/
const assert = require('assert');
function isPrime(x) {
if (x === 1 || x === 2)
return true;
for (var i = 2; i < x; i++) {
if (x !== i && x % i === 0)
return false;
else if ((i+1) === x)
return true;
}
}
function getPrimeIndex(index) {
var primes = [], i = 1;
do {
i += 1;
if (isPrime(i))
primes.push(i);
} while (primes.length < index);
return primes[primes.length - 1];
}
function solution() {
var answer = getPrimeIndex(10001);
console.log(`The solution to problem 7 is: ${answer}`);
}
assert.strictEqual(getPrimeIndex(1), 2);
assert.strictEqual(getPrimeIndex(6), 13);
solution();
/* ====== Meta ========================================= *
*
* Estimated time of completion: 20 minutes
* Search engine used: Yes. Looked up the difference
* between iteratively finding primes vs. recursively.
* Concepts learned: Practice of do-whiles
*
* Additional notes:
*
* ========================================**/