Sum All Primes_Need Help Understanding the Solution

Hello. I wondered if someone could walk me through the following solution:

  function getPrimes(max) {
    var sieve = [];
    var i;
    var j;
    var primes = [];
    for (i = 2; i <= max; ++i) {
      if (!sieve[i]) {
        // i has not been marked -- it is prime
        primes.push(i);
        for (j = i << 1; j <= max; j += i) {
          sieve[j] = true;
        }
      }
    }

    return primes;
  }

I don’t understand it at all. Thanks in advance.

1 Like

What part doesn’t make sense?

All of it really. Particularly the for-loop in the for-loop. Also, I don’t really understand what << does.

I don’t think that FCC teaches bitwise operators, but googling “javascript << operator” will get you various explanations of what it is and why you might use it.

This person solved the challenge using the Sieve of Eratosthenes.

Thanks. This is helpful.

I’m trying to create a for-loop that searches for non-primes. I thought the for-loop in this code would work, but it’s outputting primes 5 and 7 as well. Can anyone tell me what I might be doing wrong? Thanks in advance.

function sumPrimes(num) {
  let arr = [];
  let i = 2;
  while (i <= num) {
    arr.push(i);
    i++;
  }

  let container = [];
  
  for (let k = 0; k <= arr.length; k++) {
    for (let j = 2; j < num-k; j++) {  
      if ((num-k) % arr[j] == 0) {
        container.push(num-k);
      }
    }
  }
  console.log(container);  

  return num;
}

sumPrimes(10); // console.log output: 10,10,9,8,8,7,6,5,4

Trying to work your way through the logic of something is often much better done with a pen and paper. Go through every line of your code and write down what it does. This includes going through the content of loops for every time that the loop repeats. Go through and replace every k with the value it is, every j, every num-k, etc.

1 Like