Algorithm - List Prime Numbers in Javascript


Posted on Jan 19th, 2016


The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes. It works in the below manner:

function getPrimes(max) {
    var sieve = [], i, j, primes = [];
    for (i = 2; i <= max; ++i) {
        if (!sieve[i]) {
            // i has not been marked -- it is prime
            primes.push(i);
            for (j = i << 1; j <= max; j += i) {
                sieve[j] = true;
            }
        }
    }
    return primes;
}

 


Fetching Podio Data from Chrome apps spreadsheet (Javascript)Algorithm - QuickSort in Javascript

Comments
100% Complete