Skip to content

Commit 1324779

Browse files
add sieve of eratosthenes
1 parent 54fe747 commit 1324779

File tree

4 files changed

+86
-0
lines changed

4 files changed

+86
-0
lines changed

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,6 @@
2323

2424
## Хеширование
2525
1. [Хеш-таблица](https://github.com/dmitrymorozoff/algorithms-in-javascript/blob/master/source/hash-table/hash-table.js) | [Инфо](https://bitsofmind.wordpress.com/2008/07/28/introduction_in_hash_tables/)
26+
27+
## Другое
28+
1. [Решето Эратосфена](https://github.com/dmitrymorozoff/algorithms-in-javascript/blob/master/source/other/sieve-of-eratosthenes.js) | [Инфо](https://ru.wikipedia.org/wiki/%D0%A0%D0%B5%D1%88%D0%B5%D1%82%D0%BE_%D0%AD%D1%80%D0%B0%D1%82%D0%BE%D1%81%D1%84%D0%B5%D0%BD%D0%B0)

index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
<script src="./source/search/linear-search/linear-search.js" type="module"></script>
2121
<script src="./source/search/binary-search/binary-search.js" type="module"></script>
2222
<script src="./source/hash-table/hash-table.js" type="module"></script>
23+
<script src="./source/other/sieve-of-eratosthenes.js" type="module"></script>
2324
<script src="./source/main.js" type="module"></script>
2425
</body>
2526

source/other/sieve-of-eratosthenes.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
export default function sieveOfEratosthenes(n) {
2+
let primes = [];
3+
for (let i = 2; i <= n; i++) {
4+
primes[i] = true;
5+
}
6+
let p = 2;
7+
let finished = false;
8+
do {
9+
for (let i = 2 * p; i <= n; i += p) {
10+
primes[i] = false;
11+
}
12+
for (let i = p; i <= n; i++) {
13+
if (primes[i] && i > p) {
14+
p = i;
15+
break;
16+
}
17+
}
18+
} while (p * p < n);
19+
const primesValues = [];
20+
for (let i = 2; i <= n; i++) {
21+
if (primes[i]) {
22+
primesValues.push(i);
23+
}
24+
}
25+
return primesValues;
26+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import sieveOfEratosthenes from "./sieve-of-eratosthenes.js";
2+
3+
describe("sieve-of-eratosthenes", () => {
4+
test("should return true if equals", () => {
5+
const primes = [
6+
2,
7+
3,
8+
5,
9+
7,
10+
11,
11+
13,
12+
17,
13+
19,
14+
23,
15+
29,
16+
31,
17+
37,
18+
41,
19+
43,
20+
47,
21+
53,
22+
59,
23+
61,
24+
67,
25+
71,
26+
73,
27+
79,
28+
83,
29+
89,
30+
97,
31+
101,
32+
103,
33+
107,
34+
109,
35+
113,
36+
127,
37+
131,
38+
137,
39+
139,
40+
149,
41+
151,
42+
157,
43+
163,
44+
167,
45+
173,
46+
179,
47+
181,
48+
191,
49+
193,
50+
197,
51+
199
52+
];
53+
const n = 200;
54+
expect(sieveOfEratosthenes(n)).toEqual(primes);
55+
});
56+
});

0 commit comments

Comments
 (0)