-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime-numbers.js
58 lines (44 loc) · 1.05 KB
/
prime-numbers.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
'use strict';
module.exports = (primes = []) => {
const generatePrimes = index => {
if (primes.length === 0) {
primes.push(2);
}
let current = primes[primes.length - 1] + 1;
while (primes.length <= index) {
const notPrime = primes.find(prime => {
return current % prime === 0;
});
if (!notPrime) {
primes.push(current);
}
current++;
}
};
const findPrime = index => {
if (index < 0) {
throw new Error('Smallest allowed seed is 0');
}
generatePrimes(index);
return primes[index];
};
const coprime = number => {
const divisors = [];
// finds a list of common divisors
for (let i = 1; i < number / 2; i++) {
if (number % i === 0) {
divisors.push(i);
}
}
let prime = findPrime(1);
// for each prime checks if it is a divisor for a number
for (let i = 2; divisors.indexOf(prime) !== -1; i++) {
prime = findPrime(i);
}
return prime;
};
return {
find: findPrime,
coprime: coprime
};
};