R

E

A

C

T

O

xamples 

epeat

ode

pproach

ptimize

est

{ Sieve of Eratosthenes }

The Question

Write a program that uses the Sieve of Eratosthenes to find the sum of all the primes from 2 up to a given number

The Sieve of Eratosthenes is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2.

Create your range, starting at two and continuing up to and including the given limit. (i.e. [2, limit])

The algorithm consists of repeating the following over and over:

  • take the next available unmarked number in your list (it is prime)
  • mark all the multiples of that number (they are not prime)

Repeat until you have processed each number in your range.

When the algorithm terminates, all the numbers in the list that have not been marked are prime.

Huh?

Write a program that uses the Sieve of Eratosthenes to find the sum of all the primes from 2 up to a given number

Step 1

Create a range of potential primes.

function sieve (max) {
  let primes = Array(max + 1).fill(true, 2);
}

// sieve(5) --> primes = [ , , true, true, true, true]

Step 2

For each index 'i' in the array up to the square root of 'max', if you encounter a prime number at that index (a true), then find all of its multiples and mark them as composite (not prime). Optimize by starting your inner loop at 'i' squared.

function sieve (max) {
  // step 1:
  let primes = Array(max + 1).fill(true, 2);
  // step 2:
  let maxToCheck = Math.sqrt(max);
  for (let i = 2; i <= maxToCheck; i++) {
    if (primes[i]) {
      for (let multiple = i * i; multiple <= max; multiple += i) {
        primes[multiple] = false;
      }
    }
  }
}

// sieve(5) --> primes = [ , , true, true, false, true]

Step 3

function sieve (max) {
  // step 1:
  let primes = Array(max + 1).fill(true, 2);
  // step 2:
  let maxToCheck = Math.sqrt(max);
  for (let i = 2; i <= maxToCheck; i++) {
    if (primes[i]) {
      for (let multiple = i * i; multiple <= max; multiple += i) {
        primes[multiple] = false;
      }
    }
  }
  // step 3:
  return primes.reduce((sum, elem, idx) => elem ? sum + idx : sum, 0);
}

Sum the indices still marked prime

Conclusion  

Repl.it (ES6)

Repl.it (ES5)

Source from Project Euler

Sieve of Eratosthenes

By Bryan Gergen

Sieve of Eratosthenes

Technical interview problem on the Sieve of Eratosthenes

  • 1,043