Skip to content

Commit 38a5cb2

Browse files
authored
Merge pull request #351 from JimmyJoo/master
Improved SieveOfEratosthenes.js
2 parents c3bf9d6 + e23d09b commit 38a5cb2

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

Maths/SieveOfEratosthenes.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,15 @@ const sieveOfEratosthenes = (n) => {
1010
const sqrtn = Math.ceil(Math.sqrt(n))
1111
for (let i = 2; i <= sqrtn; i++) {
1212
if (primes[i]) {
13-
for (let j = 2 * i; j <= n; j += i) {
13+
for (let j = i * i; j <= n; j += i) {
14+
/*
15+
Optimization.
16+
Let j start from i * i, not 2 * i, because smaller multiples of i have been marked false.
17+
18+
For example, let i = 4.
19+
We do not have to check from 8(4 * 2) to 12(4 * 3)
20+
because they have been already marked false when i=2 and i=3.
21+
*/
1422
primes[j] = false
1523
}
1624
}

0 commit comments

Comments
 (0)