Skip to content

Instantly share code, notes, and snippets.

@nekoTheShadow
Last active August 29, 2015 14:13
Show Gist options
  • Save nekoTheShadow/d1981ab6764e16ffefc8 to your computer and use it in GitHub Desktop.
Save nekoTheShadow/d1981ab6764e16ffefc8 to your computer and use it in GitHub Desktop.
eratosthenes = function(max){
var nums = [];
var primes = [];
for(var i = 2; i <= max; i++){
nums.push(i);
}
var sqrt = Math.sqrt(max);
while(nums[0]<=sqrt){
var prime = nums.shift();
primes.push(prime);
nums = nums.filter(function(num){
return num % prime != 0
});
}
return primes.concat(nums);
}
// == main ==
console.log(eratosthenes(50));
// [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment