-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnormalSieve.js
33 lines (28 loc) · 862 Bytes
/
normalSieve.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
const normalSieve = n => {
return new Promise((resolve, reject) => {
// Eratosthenes algorithm to find all primes under n
var array = [],
upperLimit = Math.sqrt(n),
output = [];
// Make an array from 2 to (n - 1)
for (var i = 0; i < n; i++) {
array.push(true);
}
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 2; i <= upperLimit; i++) {
if (array[i]) {
for (var j = i * i; j < n; j += i) {
array[j] = false;
}
}
}
// All array[i] set to true are primes
for (var i = 2; i < n; i++) {
if (array[i]) {
output.push(i);
}
}
resolve(output.length);
});
};
module.exports = normalSieve;