Skip to content

Instantly share code, notes, and snippets.

@msanatan
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msanatan/f66bf75224df15c142fe to your computer and use it in GitHub Desktop.
Save msanatan/f66bf75224df15c142fe to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
var populateSieve = function(N) {
'use strict';
var arr = [N+1];
arr[0] = false;
arr[1] = false;
for (var i = 2; i <= N; i++) {
arr[i] = true;
}
return arr;
};
var sieveOfEratosthenes = function(N) {
'use strict';
var arr = populateSieve(N);
for (var i = 2; i <= Math.sqrt(N); i++) {
if (arr[i]) {
for (var j = Math.pow(i, 2); j <= N; j += i) {
arr[j] = false;
}
}
}
return arr;
};
var getIndexNums = function(arr, val) {
'use strict';
var indices = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i] === val) {
indices.push(i);
}
}
return indices;
};
var sieve = getIndexNums(sieveOfEratosthenes(1000), true);
var sieveSum = sieve.reduce(function(a, b) {
return a + b;
});
for (var i = 0; i < sieve.length; i++) {
console.log(sieve[i]);
}
console.log(sieveSum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment