Skip to content

Commit 2c6d147

Browse files
authored
Merge pull request #13 from ms10398/master
Added Implementation of Sieve Of Eratosthenes
2 parents 5d5d17c + ee3f3db commit 2c6d147

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Algorithms/sieveOfEratosthenes.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function sieveOfEratosthenes (n) {
2+
/*
3+
* Calculates prime numbers till a number n
4+
* :param n: Number upto which to calculate primes
5+
* :return: A boolean list contaning only primes
6+
*/
7+
let primes = new Array(n + 1);
8+
primes.fill(true); // set all as true initially
9+
primes[0] = primes[1] = false; // Handling case for 0 and 1
10+
let sqrtn = Math.ceil(Math.sqrt(n));
11+
for (let i = 2; i <= sqrtn; i++) {
12+
if (primes[i]) {
13+
for (let j = 2 * i; j <= n; j += i) {
14+
primes[j] = false;
15+
}
16+
}
17+
}
18+
return primes;
19+
}
20+
21+
function main () {
22+
let n = 69; // number till where we wish to find primes
23+
let primes = sieveOfEratosthenes(n);
24+
for (let i = 2; i <= n; i++) {
25+
if (primes[i]) {
26+
console.log(i);
27+
}
28+
}
29+
}
30+
31+
main();

0 commit comments

Comments
 (0)