Skip to content

Instantly share code, notes, and snippets.

@Costava
Created September 28, 2016 16:56
Show Gist options
  • Save Costava/df4ac5a1a6c78a8c539f44867e5ef464 to your computer and use it in GitHub Desktop.
Save Costava/df4ac5a1a6c78a8c539f44867e5ef464 to your computer and use it in GitHub Desktop.
JavaScript implementation of the Sieve of Eratosthenes for finding prime numbers
/**
* Returns a list of the prime numbers in range [0, max) in order
* Implementation of the Sieve of Eratosthenes
* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
* @param {number} max
* @returns {number[]}
*/
function getPrimeNumbers(max) {
// A list of booleans where index 2 being true corresponds to 2 being prime
var isPrime = [];
// Initial population of isPrime
for (var i = 0; i < max; i += 1) {
if (i != 0 && i != 1) {
isPrime.push(true);
}
else {
isPrime.push(false);
}
}
// Iterate over entire list
// Element => true if index is prime else false
for (var i = 0; i < max; i += 1) {
if (isPrime[i]) {
for (var j = i + i; j < max; j += i) {
isPrime[j] = false;
}
}
}
var primes = [];
// Assemble list of primes
for (var i = 0; i < max; i += 1) {
if (isPrime[i]) {
primes.push(i);
}
}
return primes;
}
The MIT License (MIT)
Copyright (c) 2016 Costava
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@Costava
Copy link
Author

Costava commented Sep 28, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment