EN
JavaScript - finding prime numbers with Sieve of Eratosthenes
7 points
In this short article, we would like to show how to find prime numbers using Sieve of Eratosthenes and JavaScript.
The main idea of the Sieve of Eratosthenes algorithm is to:
- generate array of numbers from
2
toN
(whereN
is maximal number that we want to check if is prime number), - remove all numbers from the array that are multiplications:
- of
2
giving4
,6
,8
,10
, ..., N - of
3
giving6
,9
,12
,15
, ..., N - of
4
giving8
,12
,16
,20
, ..., N - ...
- up to
Math.sqrt(N)
- of
- the numbers that were not removed are prime numbers.
Main disadvantage of Sieve of Eratosthenes algorithm is necessary to have big amount of operating memory when we want to find really big numbers.
Main advantage of Sieve of Eratosthenes algorithm is simplicity.
2 | 3 | 5 | 7 | ||||||
11 | 13 | 17 | 19 | ||||||
23 | 29 | ||||||||
31 | 37 | ||||||||
41 | 43 | 47 | |||||||
53 | 59 | ||||||||
61 | 67 | ||||||||
71 | 73 | 79 | |||||||
83 | 89 | ||||||||
97 |
In this section removed numbers we mark with false
value.
xxxxxxxxxx
1
const findPrimeNumbers = (max) => {
2
const places = Array(max);
3
places[0] = false;
4
places[1] = false;
5
for (let i = 2; i < max; ++i) {
6
places[i] = true;
7
}
8
const limit = Math.sqrt(max);
9
for (let i = 2; i < limit; ++i) {
10
if (places[i]) {
11
for (let j = i + i; j < max; j += i) {
12
places[j] = false;
13
}
14
}
15
}
16
const numbers = new Array();
17
for (let i = 2; i < max; ++i) {
18
if (places[i]) {
19
numbers.push(i);
20
}
21
}
22
return numbers;
23
};
24
25
26
// Usage example:
27
28
console.log(findPrimeNumbers(100)); // from 0 to 100 (excluded)
29
console.log(findPrimeNumbers(200)); // from 0 to 200 (excluded)
In this section we have preseted animation that shows what not prime numbers are removed during next iterations.
xxxxxxxxxx
1
const detectPrimeNumbers = async (max, callback) => {
2
const places = Array(max);
3
places[0] = false;
4
places[1] = false;
5
for (let i = 2; i < max; ++i) {
6
places[i] = true;
7
}
8
await callback(null, places, false);
9
const limit = Math.sqrt(max);
10
for (let i = 2; i < limit; ++i) {
11
if (places[i]) {
12
for (let j = i + i; j < max; j += i) {
13
places[j] = false;
14
}
15
}
16
await callback(i, places, false);
17
}
18
await callback(null, places, true);
19
};
20
21
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
22
23
detectPrimeNumbers(100, async (candidate, places, completed) => {
24
let text = '';
25
if (candidate) {
26
text += `removing ${candidate} * n`;
27
}
28
if (completed) {
29
text += 'Prime numbers detected!';
30
}
31
for (let i = 0; i < places.length; ++i) {
32
if (i % 10 === 0) {
33
text += '\n|';
34
}
35
text += ` ${places[i] ? (i < 10 ? ' ' + i : i) : ' '} |`;
36
}
37
console.clear();
38
console.log(text);
39
await sleep(1000);
40
});