Return to Snippet

Revision: 35984
at November 16, 2010 18:28 by pmigueld


Updated Code
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;
};

Revision: 35983
at November 15, 2010 23:21 by pmigueld


Initial Code
var getPrimes = function (n) {
    var numbers = [],
        multiple, i, j,
        square = function (x) { return x * x; };
        
    for(var i = 2; i <= n; i++) {
        numbers.push(i);
    }
    
    j = 0;
    while(square(numbers[j]) < n) {
        multiple = numbers[j];
        
        i = 0;
        while(i < numbers.length) {	
            if(numbers[i] % multiple === 0) {
                if(numbers[i] === multiple) { i++; continue; }
                numbers.splice(i, 1);
            }
            i++;
        }
        j++;
    }
    
    return numbers;
};

Initial URL

                                

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

Initial Title
Sieve of Eratosthenes

Initial Tags
math

Initial Language
JavaScript