9
9
* sieveOfEratosthenes(20) // ====> [2, 3, 5, 7, 11, 13, 17, 19]
10
10
*/
11
11
function sieveOfEratosthenes ( max ) {
12
- if ( max < 2 ) return [ ] ;
12
+ if ( max < 2 ) return [ ]
13
13
14
- // Initialize sieve array, false means "potentially prime"
15
- const sieve = Array ( max + 1 ) . fill ( false ) ;
16
- const primes = [ 2 ] ; // Include 2, the only even prime
14
+ // Initialize sieve array, false means "potentially prime"
15
+ const sieve = Array ( max + 1 ) . fill ( false )
16
+ const primes = [ 2 ] // Include 2, the only even prime
17
17
18
- // start from 3 to mark odd numbers only
18
+ // start from 3 to mark odd numbers only
19
19
for ( let i = 3 ; i * i <= max ; i += 2 ) {
20
20
if ( ! sieve [ i ] ) {
21
-
22
21
// Mark all odd multiples of i starting from i*i as composite
23
22
for ( let j = i * i ; j <= max ; j += 2 * i ) {
24
- sieve [ j ] = true ;
23
+ sieve [ j ] = true
25
24
}
26
25
}
27
26
}
28
27
29
28
// Collect all odd primes greater than 2
30
29
for ( let k = 3 ; k <= max ; k += 2 ) {
31
- if ( ! sieve [ k ] ) primes . push ( k ) ;
30
+ if ( ! sieve [ k ] ) primes . push ( k )
32
31
}
33
32
34
- return primes ;
33
+ return primes
35
34
}
36
35
37
- export { sieveOfEratosthenes } ;
38
-
36
+ export { sieveOfEratosthenes }
39
37
40
38
// i reduced the memory usage by half -> removed the even numbers from the sieve array
41
39
// i reduced the number of iterations by half -> iterating only over odd numbers
42
40
// i reduced the number of inner loop iterations by half -> marking only odd multiples of each prime
43
- // overall time complexity remains O(n log log n) but with a smaller constant factor due to fewer operations
41
+ // overall time complexity remains O(n log log n) but with a smaller constant factor due to fewer operations
0 commit comments