forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinearSieve.js
More file actions
Latest commit
24 lines (23 loc) · 629 Bytes
/
Copy pathLinearSieve.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
constLinearSieve=(n)=>{
/*
* Calculates prime numbers till a number n
* Time Complexity: O(n)
* Explanation: https://cp-algorithms.com/algebra/prime-sieve-linear.html
* :param n: Number up to which to calculate primes
* :return: A list containing only primes
*/
constisnPrime=newArray(n+1)
isnPrime[0]=isnPrime[1]=true
constprimes=[]
for(leti=2;i<=n;i++){
if(!isnPrime[i])primes.push(i)
for(constpofprimes){
constk=i*p
if(k>n)break
isnPrime[k]=true
if(i%p===0)break
}
}
returnprimes
}
export{LinearSieve}