Skip to content

Added Implementation of Sieve Of Eratosthenes #13

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 5, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Algorithms/sieveOfEratosthenes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function sieveOfEratosthenes (n) {
/*
* Calculates prime numbers till a number n
* :param n: Number upto which to calculate primes
* :return: A boolean list contaning only primes
*/
let primes = new Array(n + 1);
primes.fill(true); // set all as true initially
primes[0] = primes[1] = false; // Handling case for 0 and 1
let sqrtn = Math.ceil(Math.sqrt(n));
for (let i = 2; i <= sqrtn; i++) {
if (primes[i]) {
for (let j = 2 * i; j <= n; j += i) {
primes[j] = false;
}
}
}
return primes;
}

function main () {
let n = 69; // number till where we wish to find primes
let primes = sieveOfEratosthenes(n);
for (let i = 2; i <= n; i++) {
if (primes[i]) {
console.log(i);
}
}
}

main();