# Doubts about a solution : Sum All Primes SPOILER

Hi,

I got to solve this problem after a while, but I realized that I am repeating myself to much ( I think). So I was trying to find out how others solved the problem. In the guide, there is a basic, intermediate and advanced solution. But there are things I don’t understand. I would appreciate if someone could explain them for me.

This is my solution:

``````function sumPrimes(num) {
var newArray = [];
for(var i = 2; i <= num; i++){
if(i == 2){
newArray.push(i);
} else if( i % 2 != 0){
var counter = 0;
var j = 3;
if(i == 3){
newArray.push(i);
} else {
while(counter == 0 && j < i){
if(i % j == 0){
counter++;
} else {
j = j + 2;
}
}
if(counter == 0){
newArray.push(i);
}

}
}
}
var sum = newArray.reduce(function(a,b){return a + b;})
return sum;
}

sumPrimes(10);
``````

This is the basic solution on the guide:

``````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;
}

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

return res;
}

// test here
sumPrimes(10);
``````

I am not understanding at all, why the sieve array is initiated, but nothing is ever “pushed” into the array, I mean, the array is empty the whole time, isn’t it?

what is the code trying to do with:

`if (!sieve[i]){...}`

Also, why does the code use a bitwise operator?

`for (j = i << 1; j <= max; j += i)`

I appreciate any help.

edit: I appreciate if anybody could explain me how to blur things up. I have tried to blur the solutions but they don’t get blurred, but everythings becomes weird.

2 Likes

Your code has been blurred out to avoid spoiling a full working solution for other campers who may not yet want to see a complete solution. In the future, if you post a full passing solution to a challenge and have questions about it, please surround it with `[spoiler]` and `[/spoiler]` tags on the line above and below your solution code.

Thank you.

1 Like

I’d like to know that too! Why is no one else wondering about this? Is there something obvious I’m missing?
Btw, did you find out how it works or could someone explain?

1 Like

Here a good explanation on shift operators (<<) that helped me understand it better:

j = i << 1 is basically just a complicated way of saying j = i * 2.
It does the exact same thing!