-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15-first-n-primes.js
58 lines (45 loc) · 1.31 KB
/
15-first-n-primes.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
/*
* PROBLEM #15: First n primes
*
* Write a recursive function called `firstNPrimes` that takes in a number
* and returns the first n prime numbers from an (optional) starting number
*
* Examples:
*
* firstNPrimes(3, 2) // returns [2, 3, 5]
* firstNPrimes(5, 4) // returns [5, 7, 11, 13, 17]
*
*/
const isPrime = (num) => {
if (num === 2) return true;
if (num <= 1 || num % 2 === 0) return false;
for (let i = 3; i < Math.floor(num / 2); i += 2) {
if (num % i === 0) return false;
}
return true;
};
const firstNPrimes = (counter, iterator = 2) => {
if (counter <= 0) return;
const nextIterator =
iterator < 3 || iterator % 2 === 0 ? iterator + 1 : iterator + 2;
if (isPrime(iterator)) {
const nextPrime = firstNPrimes(counter - 1, nextIterator);
return typeof nextPrime === 'undefined'
? [iterator]
: [iterator].concat(nextPrime);
}
return firstNPrimes(counter, nextIterator);
};
/*
// SOLUTION WITHOUT USING RECURSION
const firstNPrimes = (counter, iterator = 2) => {
if (counter <= 0) return;
const arrayOfPrimes = [];
while (arrayOfPrimes.length < counter) {
if (isPrime(iterator)) arrayOfPrimes.push(iterator);
iterator = iterator < 3 || iterator % 2 === 0 ? iterator + 1 : iterator + 2;
}
return arrayOfPrimes;
};
*/
module.exports = firstNPrimes;