99 * sieveOfEratosthenes(20) // ====> [2, 3, 5, 7, 11, 13, 17, 19]
1010 */
1111function sieveOfEratosthenes ( max ) {
12- if ( max < 2 ) return [ ] ;
12+ if ( max < 2 ) return [ ]
1313
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
1717
18- // start from 3 to mark odd numbers only
18+ // start from 3 to mark odd numbers only
1919 for ( let i = 3 ; i * i <= max ; i += 2 ) {
2020 if ( ! sieve [ i ] ) {
21-
2221 // Mark all odd multiples of i starting from i*i as composite
2322 for ( let j = i * i ; j <= max ; j += 2 * i ) {
24- sieve [ j ] = true ;
23+ sieve [ j ] = true
2524 }
2625 }
2726 }
2827
2928 // Collect all odd primes greater than 2
3029 for ( let k = 3 ; k <= max ; k += 2 ) {
31- if ( ! sieve [ k ] ) primes . push ( k ) ;
30+ if ( ! sieve [ k ] ) primes . push ( k )
3231 }
3332
34- return primes ;
33+ return primes
3534}
3635
37- export { sieveOfEratosthenes } ;
38-
36+ export { sieveOfEratosthenes }
3937
4038// i reduced the memory usage by half -> removed the even numbers from the sieve array
4139// i reduced the number of iterations by half -> iterating only over odd numbers
4240// 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