Build a Prime Number Sum Calculator - Build a Prime Number Sum Calculator

Tell us what’s happening:

Are there any other approaches that would make this more compact and easier to read?

Your code so far

const sumPrimes = (num) => {
  let totalPrimes = 0;
  let numArr = [];

  // Ignoring less than 2 and consedring 2 >>

  if (num <= 1) {
    return 0;
  } else if (num === 2) {
    return 2;
  }

  // Creating an array for numbers less than (num) inclusive >>

  for (let i = 2; i <= num; i++) {
    numArr.push(i);
  }

  // Testing every array number to see if it's divisible by any other number >> 

  for (let j of numArr) {
    let tempNum = j;
    for (let i = 2; i < tempNum; i++) {
      if (tempNum % i === 0) {
        tempNum = 0;
      }
    }
    totalPrimes += tempNum;
  }
  return totalPrimes;
};

console.log(sumPrimes(977));

Your browser information:

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

Challenge Information:

Build a Prime Number Sum Calculator - Build a Prime Number Sum Calculator

Hi @yasser-diab ,

We have blurred this solution (with [spoiler][/spoiler] tags) so that users who have not completed this challenge can read the discussion in this thread without giving away the solution.

The category has also been changed to “Code Feedback”.

Happy coding!

2 Likes

Consider two things:

  • What numArr is used for.
  • What happens, when tempNum % i === 0. What does it imply for further iterations in the loop.