/ Published in: JavaScript
Returns an array of all the prime numbers up to (n) using an implementation of the Sieve of Eratosthenes.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var getPrimes = function (n) { var numbers = [], multiple, i, j, len, square = function (x) { return x * x; }; for(i = 2; i <= n; i++) { numbers.push(i); } for(j = 0; square(numbers[j]) < n; j++) { multiple = numbers[j]; for(i = 0, len = numbers.length; i < len; i++) { if(numbers[i] % multiple === 0) { if(numbers[i] === multiple) { i++; continue; } numbers.splice(i, 1); } } } return numbers; };