Following Implementation of Sieve of Eratosthenes but last test won´t pass

Intermediate Algorithm Scripting: Sum All Primes

I´m looking for an advice in what more should I implement to pass the last test (sumPrimes(977))

While the first two tests are passed, Last test with my code gives different sum of primes than the one FCC is asking. The problem is I have followed it´s tutorial about finding the primes (https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)upto the number 30 and the code delivers the same as the wikipedia´s example.

`function sumPrimes(num) {
  var arrayNum = [];
	var counter = 0

        for (var i = 0; i < num; i++){
        counter ++
        arrayNum.push(counter)
            }
		arrayNum = arrayNum.slice(1,)

	for (var i = 0; i < arrayNum.length; i++){
        if (arrayNum[i] % 2 == 0){
				if (arrayNum[i] === 2){1==1}
				else {delete arrayNum[i]}
				}
            }

		for (var i = 0; i < arrayNum.length; i++){
        if (arrayNum[i] % 3 == 0){
				if (arrayNum[i] === 3){1==1}
				else {delete arrayNum[i]}
				}
            }

            for (var i = 0; i < arrayNum.length; i++){
            if (arrayNum[i] % 5 == 0){
                    if (arrayNum[i] === 5){1==1}
                    else {delete arrayNum[i]}
                    }
                }

			
	
	arrayNum = arrayNum.filter(x => Number.isInteger(x))

	var sum= arrayNum.reduce((x,y) => {return x + y})
	return sum
}

sumPrimes(977);`

damn i think i know now what is wrong. Apparently to really get all primes in up to ANY number I should follow best this, right?:

  1. Create a list of consecutive integers from 2 through n: (2, 3, 4, …, n ).
  2. Initially, let p equal 2, the smallest prime number.
  3. Enumerate the multiples of p by counting in increments of p from 2 p to n, and mark them in the list (these will be 2 p , 3 p , 4 p , …; the p itself should not be marked).
  4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this new number (which is the next prime), and repeat from step 3.
  5. When the algorithm terminates, the numbers remaining not marked in the list are all the primes below n.

the problem is i didn´t do that but instead I followed the example below in where they guide you to search for primes up to the number 30, but in that case only is needed to search for multiples of 2, 3 and 5

Have i got it correctly guys?

1 Like