forked from davidflanagan/jstdg7
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsieve.js
More file actions
13 lines (13 loc) · 708 Bytes
/
Copy pathsieve.js
File metadata and controls
13 lines (13 loc) · 708 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
// Return the largest prime smaller than n, using the sieve of Eratosthenes
function sieve(n) {
let a = new Uint8Array(n+1); // a[x] will be 1 if x is composite
let max = Math.floor(Math.sqrt(n)); // Don't do factors higher than this
let p = 2; // 2 is the first prime
while(p <= max) { // For primes less than max
for(let i = 2*p; i <= n; i += p) // Mark multiples of p as composite
a[i] = 1;
while(a[++p]) /* empty */; // The next unmarked index is prime
}
while(a[n]) n--; // Loop backward to find the last prime
return n; // And return it
}