Last active
August 29, 2015 14:09
-
-
Save msanatan/f66bf75224df15c142fe to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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