Sum all primed (reduce function)

Sum all primed (reduce function)
0

#1

Please help, my array returns correct values for prime numbers till the provided num. However, my reduce function is way off!
It works fine for some num values but not others like 977
Can any one see where I’m I going wrong?

Here is my code:

function sumPrimes(num) {
  Array.prototype.getAll = Array.prototype.getAll || function(n) {
    let count = 2;
    do {
      this.push(count);
      count++;
    }while(count < n);

  }
  function checkDiv(n) {
    for(let i=2; i<=9; i++) {
      if(n !== i) {
        if(n%i === 0) return false;
      }
    }
    return true;
  }
  
  let allNums = [];
  allNums.getAll(num);
  
  
  return allNums.filter(e => {
     return checkDiv(e);
  
  }).reduce( (acc, a) => acc+a);
}

console.log(sumPrimes(977));
//sumPrimes(977) should return 73156     but returns 107812 !!

#2

Hello,

If I understand your function correctly function checkDiv(n) is a test for prime.

I believe that it does not successfully filter out non-primes so your sum is higher than expected.

Also your range method getAll is stops one number short


#3

so you check if a number is divisible by 2 thru 9. What if it’s smallest factor is 13? I suggest taking a few and wikipedia ‘sieve of archimedes’.


#4

Thanks for your response bud. Yeh that’s interesting I also tried Wilson’s Theorem for checking for primes and it wouldn’t work past numbers 23! The following code shows changes


.
.
  /*
  4! = 4×3×2×1
  n! = n×(n−1)×(n−2)...×2×1
  */
  
  function getFact(n) {
    let f = 1; 
    let c = n;
    while(c >= 1) {
      f *= c;
      c--;
    }
    return f
  }
.
.
.
  /*
  if (n-1)! == -1(mod n) then n is prime 
  */
  function checkPrime(n) {
    if(n > 1) { //console.log(n);
      if(getFact(n-1) % n === n-1) return true;
    }
    return false;
  }

 return allNums.filter(e => {
     return checkPrime(e);
  
  }).reduce((acc, e) => acc+e);
}
  

#5

But finally solved it with a simple method:

  function checkPrime(n) {
    if(n > 1) {
      for(let i=2; i<n; i++) {
        if(n%i === 0) return false;
      }
      return true;
    }
    return false;
  }
  

I seem to have over complicated it. Still couldn’t exactly figure out why the previous didn’t work, but oh will.
cheers :slight_smile: