Posted By

pmigueld on 11/15/10


Tagged

math numbers algorithm prime eratosthenes


Versions (?)

Sieve of Eratosthenes


 / Published in: JavaScript
 

Returns an array of all the prime numbers up to (n) using an implementation of the Sieve of Eratosthenes.

  1. var getPrimes = function (n) {
  2. var numbers = [],
  3. multiple, i, j, len,
  4. square = function (x) { return x * x; };
  5.  
  6. for(i = 2; i <= n; i++) {
  7. numbers.push(i);
  8. }
  9.  
  10. for(j = 0; square(numbers[j]) < n; j++) {
  11. multiple = numbers[j];
  12. for(i = 0, len = numbers.length; i < len; i++) {
  13. if(numbers[i] % multiple === 0) {
  14. if(numbers[i] === multiple) { i++; continue; }
  15. numbers.splice(i, 1);
  16. }
  17. }
  18. }
  19. return numbers;
  20. };

Report this snippet  

You need to login to post a comment.