Skip to content

Instantly share code, notes, and snippets.

@LucianBuzzo
Created March 6, 2023 15:21
Show Gist options
  • Select an option

  • Save LucianBuzzo/b9ff584ae6ff741659a8bd11479dace1 to your computer and use it in GitHub Desktop.

Select an option

Save LucianBuzzo/b9ff584ae6ff741659a8bd11479dace1 to your computer and use it in GitHub Desktop.
const primeSeive = (n) => {
const primes = []
// Start with an array of all numbers between 2 and n
let buf = Array(n - 1).fill().map((_, i) => i + 2);
let pointer = 0;
while (pointer < buf.length) {
const p = buf[pointer];
// Push the prime
primes.push(p);
// Remove all multiples of p from the buf skipping the first one
for (let i = pointer + p; i < buf.length; i += p) {
buf[i] = null;
}
// Advance the pointer to the next non null number;
do {
pointer += 1;
} while(buf[pointer] === null)
}
return primes;
}
console.log(primeSeive(100));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment