Sum all primes - intermediate algorithm

Sum all primes - intermediate algorithm
0

#1

I need some help with this algorithm. My code works for sumPrimes(10) but not for sumPrimes(977), can anyone help me understand what’s wrong with it?

function sumPrimes(num) {
  var result = 0;
  var arr = [];
  
  for (var i = 2; i <= num; i++) {
    if ( i !== 2 && i % 2 === 0) {
      continue;
    }
    else if (i !== 3 && i % 3 === 0) {
      continue;
    }
    else if (i !== 5 && i % 5 === 0) {
      continue;
    }
    else if (i !== 7 && i % 7 === 0) {
      continue;
    }
    else {
      arr.push(i);
    }
  }
  
  for (var j = 0; j < arr.length; j++) {  
    result += arr[j];
  } 
 
  return result;
}

#2

U migh find this useful

U have bound in variable num
Then like u do transvere all numbers till that number
And add inner loop that goes from 2 to root of the current number in outer loop ( i )

Etc if ur i = 16
U will go till root cause after that start pairs
0, 1,2,3,------4 then stop because 4 have pair with 8 etc

Ur algorithm doesnt work cause there is numbers like 121


√121 = 11
Then use ur inner loop


#3

function checkPrime(num1)
{
var y = 2;
for(y; y<(num1/2) ; y++)
{
if((num1)%y === 0 )
{
return 0;
} // if
}
if(y === (num1/2))
return num1;
}// function checkPrime

function sumPrime(num)
{
var result = 0;
var x=2;

for( x; x<num; x++)
{
result = result+ checkPrime(num);
}
return result;
}

//----- Above code should work for you… You can call to sumPrime() function… that’s all…
check for syntax as I don’t know which language you are using… Logic will remain same ---- //


#4

Thank you! I now understand where I went wrong