Created
August 4, 2023 22:19
-
-
Save fabiospampinato/7bd5e6b1f2e9cd9ed4674575c41df5c8 to your computer and use it in GitHub Desktop.
A little Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sieve = ( size ) => { | |
//TODO: add windowing for the buffer, allocating a fixed-size buffer that gets repopulated when needed | |
const buffer = new Uint8Array ( Math.ceil ( size / 8 ) ).fill ( 255 ); | |
const primes = []; | |
let prev = 2; | |
for ( let i = 2; i <= size; i++ ) { | |
const index = Math.floor ( i / 8 ); | |
const offset = i % 8; | |
if ( buffer[index] & ( 1 << offset ) ) { // is prime | |
// const delta = i - prev; | |
// primes.push ( delta ); | |
// prev = i; | |
primes.push ( i ); | |
for ( let j = i + i; j <= size; j += i ) { | |
const index = Math.floor ( j / 8 ); | |
const offset = j % 8; | |
buffer[index] &=~ ( 1 << offset ); | |
} | |
} | |
} | |
console.log ( primes.join ( '\n' ) ); | |
}; | |
sieve ( 1_000_000 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment