Skip to content

Instantly share code, notes, and snippets.

@adrian154
Created October 27, 2021 04:47
Show Gist options
  • Select an option

  • Save adrian154/a3a05e83477504f83eabf3b508632a73 to your computer and use it in GitHub Desktop.

Select an option

Save adrian154/a3a05e83477504f83eabf3b508632a73 to your computer and use it in GitHub Desktop.
const nthPrime = (n) => {
// conservative upper bound for nth prime is n log(n log n)
// works for all n >= 6
const max = Math.floor(n * Math.log(n * Math.log(n)));
// allocate sieve
const sieve = new Uint8Array(Math.ceil(max / 8)).fill(0);
// we need to keep track of how many primes we've encountered so far because the upper bound probably includes more than `n` primes
let maxPrime, nth = 0;
for(let i = 2; i < max; i++) {
// if i is not marked...
if((sieve[Math.floor(i / 8)] & (1 << i % 8)) == 0) {
maxPrime = i;
nth++;
if(nth == n) return maxPrime;
// mark all
for(let j = i; j < max; j += i) {
sieve[Math.floor(j / 8)] |= (1 << (j % 8));
}
}
}
return maxPrime;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment