I don't understand it

Tell us what’s happening:
I looked for the hint and I don’t understand the code given there to find the prime numbers. Please help me understand the code…
I don’t understand the code form line 11

Your code so far


function sumPrimes(num) {
  var res = 0;

  // Function to get the primes up to max in an array
  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;
  }

  // Add the primes
  var primes = getPrimes(num);
  for (var p = 0; p < primes.length; p++) {
    res += primes[p];
  }

  return res;
}

// test here
sumPrimes(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0.

Challenge: Sum All Primes

Link to the challenge:

this seems to be the sieve of erathostenes implemented in JavaScript

Hi @urfrenznimubro!

I have added spoiler tags since this is a working solution.

Thank you all for helping but I was saying that I dont understand the code

for (j = i << 1; j <= max; j += i) {
    sieve[j] = true;
 }

I don’t understand that j = i << 1; j <= max; j+= i

Are you familiar with bitshifts? That says to shift over digits in binary, which means multiply by 2.

Did you mean converting a number to binary?

No. The number is stored as binary. <<1 shifts everything in the binary representation one to the left, which is the same as multiplying by two. If I recall correctly the Wikipedia article on bitwise operations is pretty good.

Oh okay, so the code here uses the bitshift to find out the prime numbers?

The code uses a bitshift to start j at i*2 and then sets every multiple of j that’s less than or equal to max as ‘true’, which I’m assuming means not prime.

Alright, thank you so much for letting me know about that “bitshift” and for helping me. :smiley:

1 Like