Last active
May 6, 2020 15:36
-
-
Save aeisenberg/5b13c32189953d289a53ef7fe40752da to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This function implements the Sieve of Eratosthenes. | |
* https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes | |
* | |
* @param {number} lastNumber The upper bound of the number to check | |
* @return {number[]} An array of prime numbers less than lastNumber | |
*/ | |
function sieve(lastNumber = 1000) { | |
// Create an array and fill it with true | |
// Important! the array's length is one more than lastNumber so that | |
// the array index matches the value of the number we are checking. | |
const isPrimeArray = new Array(lastNumber + 1).fill(true); | |
// We know that 0 and 1 are not prime, so set it here. | |
isPrimeArray[0] = false; | |
isPrimeArray[1] = false; | |
// The upper bound of what we need to check is the square root of lastNumber | |
const squrtLast = Math.floor(lastNumber ** 0.5); | |
for (var i = 0; i <= squrtLast; i++) { | |
// Only go through this loop is we don't yet know if i is prime | |
if (isPrimeArray[i]) { | |
for (var j = i ** 2; j < isPrimeArray.length; j += i) { | |
// All multiples of i are not prime | |
isPrimeArray[j] = false; | |
} | |
} | |
} | |
// We need to convert the array from true/false values to the actual numbers | |
// that are prime. Do this here | |
return isPrimeArray | |
// first: convert true values to their index and false values to undefined | |
.map((isPrime, index) => isPrime ? index : undefined) | |
// filter out all undefined values. | |
// What remains are the prime numbers | |
.filter(index => index) | |
// Reduce the array to find the sum of all the prime numbers | |
.reduce((sum, val) => sum += val, 0); | |
} | |
const num = 1000; | |
const sum = sieve(num); | |
console.log(`The sum of the prime numbers from 0 to ${num} is ${sum}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment