Intermediate Algorithm Scripting - Sum All Primes

Tell us what’s happening:
Hello guys,
I should find the sum of all prime numbers that are less than or equal to num. I came up with solution but I do not know why it does not work, can anyone help me? (I know my approach is not best(It works when “num” is less than 90 ))

Your code so far

function sumPrimes(num) {
  let sum = null
  let array = []
  for( let i = 2 ; i <= num ; i++ ){
    for(let j = 1; j <= i; j++){
      if( j !== 1  ){
        if( i !== j ){
          if(i % j === 0 ){
         array.push(i)
         i++
          }
        }
      }
    }
  }

  for(let k = 2 ; k <= num ;k++){
    if(array.indexOf(k) === -1){
      sum += k
    }
  }

  return sum;
}

sumPrimes(977);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36

Challenge: Intermediate Algorithm Scripting - Sum All Primes

Link to the challenge:

I have applied more standard formatting to your code:

function sumPrimes(num) {
  let sum = 0;
  let array = [];
  for (let i = 2; i <= num; i++) {
    for (let j = 1; j <= i; j++) {
      if (j !== 1) {
        if (i !== j) {
          if (i % j === 0) {
            array.push(i);
            i++;
          }
        }
      }
    }
  }

  for (let k = 2; k <= num; k++) {
    if (array.indexOf(k) === -1) {
      sum += k;
    }
  }

  return sum;
}

sumPrimes(10);

Changing the loop iteration variable inside of the loop is a big red flag for a potential bug.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.