Sieve of Eratosthenes


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.