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 Erat(max){
    var primes = [];
    for (i=0; i< max; i++){
        primes.push(true)
    }
}

// Erat(5) --> [true,true,true,true,true]

Step 2

For each index in the array,

if you encounter a prime number at that index (a true)

then find all of it's multiples and mark them as not prime.

function Erat(max){
    //step 1 stuff:
    var primes = []
    for (i=0; i< max; i++){
	primes.push(true)
    }
    //step 2 stuff:
    for(var x=2; x<primes.length; x++){
        var multiple = x;
	while(multiple < max){
	    multiple += x;
            if(primes[multiple-1]){
		primes[multiple-1] = false
            }
	}	
    }
    //Erat(5) --> primes = [true, true, true, false, true]
}

Step 3

var sum = 0
primes.forEach(function(prime, idx, array){
    if(idx==1){
        sum -= 1
    }
    if(prime){
        sum += idx+1
    }
})
return sum

add it up

The Whole Kit-And-Kaboodle

function Erat(max){
	//Step 1
	var primes = []
	for (i=0; i< max; i++){
		primes.push(true)
	}
	//Step 2
	for(var x=2; x<primes.length; x++){
		var multiple = x
		while(multiple < max){
			multiple += x
			if(primes[multiple-1]){
				primes[multiple-1] = false
			}
		}	
	}
        //Step 3
	var sum = 0
	primes.forEach(function(prime, idx, array){
		if(idx==1){
			sum -= 1
		}
		if(prime){
			sum += idx+1
		}
	})
	return sum
}

Conclusion  

Solution on Repl.it

Source from Project Euler

Sieve of Eratosthenes

By Sarah Muenzinger

Sieve of Eratosthenes

Technical interview problem on the Sieve of Eratosthenes

  • 1,722