Sum All Primes Clarification

function sumPrimes(num) {
  var primeArr = [];
  // array to store prime numbers
  var numArr = [];
  // array to store all numbers up to prime number
  for (var i = 2; i <= num; ++i) {
  // SO Sieve of Eratosthenes implementation 
    if (!numArr[i]) {
    // i has not been marked -- it is prime
      primeArr.push(i);
      for (var x = i << 1; x <= num; x += i) {
        numArr[x] = true;
         }
      }
   } 
   var primeSum = primeArr.reduce(function(total,currentVal) {
     // sum all prime numbers together & store result
     return total + currentVal;
   });
   return primeSum;
   // return result
}

sumPrimes(10);

i looked at the forum help for this as i’ve been struggling with it for some time. i’ll admit math isn’t really my strong suit.

Anyway, i’ll be 100% honest, i implemented someones elses alg for finding primes.

I know the general rule is “not to copy others code”, but the forum help article by Rafase282 seems to suggest that it’s ok in this instance?

Can anyone confirm that this is definitely the case?

By “don’t copy” they mean to not just blindly copy without understanding or attempting to work through it on your own. Otherwise, looking up others’ algorithms and implementing them is at least half of what programming is about.

That’s cool man, i always strive to do that & to document my solutions so other’s could understand it aswell. Infact i’ve only ever done what i mentioned for this challenge alone.

I know it’s normal behaviour in the wider scope of programming in general, but i just wanted to clarify in terms of the course. Thanks for the reply!

What does the following code mean:

var sieve = []; if (!sieve[i]) {

Because in my head it means “If NOT sieve at index i, then carry on the loop”.
However sieve has no numbers in it yet? Im a bit confuzzled… Can someone please help?

1 Like

!sieve[i] is checked whether it’s truthy or falsy inside the if-condition (it doesn’t matter if it’s boolean or not; what matters is its “truthiness” or “falsiness”). The ! coerces sieve[i] into a boolean value. If sieve[i] has no value, it’s undefined (which is falsy), then because of the !, the entire thing is true.

Ah, ok so basically it means that sieve[i] will always be true?

As in saying if sieve[i] is not not true?

Not necessarily. If sieve[i] has a nonzero value, !sieve[i] will be false (zero is a falsy value).