-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathLinearSieve.js
More file actions
24 lines (23 loc) · 629 Bytes
/
LinearSieve.js
File metadata and controls
24 lines (23 loc) · 629 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const LinearSieve = (n) => {
/*
* Calculates prime numbers till a number n
* Time Complexity: O(n)
* Explanation: https://un5ne6zjpaf9eyxctzu28.julianrbryant.com/algebra/prime-sieve-linear.html
* :param n: Number up to which to calculate primes
* :return: A list containing only primes
*/
const isnPrime = new Array(n + 1)
isnPrime[0] = isnPrime[1] = true
const primes = []
for (let i = 2; i <= n; i++) {
if (!isnPrime[i]) primes.push(i)
for (const p of primes) {
const k = i * p
if (k > n) break
isnPrime[k] = true
if (i % p === 0) break
}
}
return primes
}
export { LinearSieve }