Skip to content

Instantly share code, notes, and snippets.

@livingston
Created April 25, 2010 06:17
Show Gist options
  • Save livingston/378199 to your computer and use it in GitHub Desktop.
Save livingston/378199 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
/* Sieve of Eratosthenes 1.1
* Author: Livingston Samuel, [email protected]
* Date: 24th April 2010
* Description: the Sieve of Eratosthenes (Greek: κόσκινον Ἐρατοσθένους) is a simple, ancient algorithm for finding all prime numbers up to a specified integer.
*
* http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
*/
(function () {
var compactArray = function(arr) {
var result = [], currentItem,
l = arr.length;
while(l--) {
currentItem = arr[l];
currentItem === undefined || currentItem === null || result.push(currentItem);
}
return result.reverse();
},
sieveOfEratosthenes = function (limit) {
if(limit > 1E6) { return; }
var numbers = [], l = limit, i = 2,
removeMultiple = function(num) {
var l = limit, min = Math.pow(num, 2);
while(l-- && l > min) {
if(l%num === 0) {
numbers[l] = null;
}
}
numbers[min] = null;
};
//populate
while(l--) {
numbers.push(l);
}
numbers.reverse();
while(i < limit) {
removeMultiple(i++);
}
numbers[0] = null;
numbers[1] = null;
return compactArray(numbers);
};
console.log(sieveOfEratosthenes(1000));
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment