Https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes

Tell us what’s happening:
Describe your issue in detail here.
Can someone explain the purpose of isPrime function and the Math.sqrt() method?

  **Your code so far**

function sumPrimes(num) {
// Helper function to check primality
function isPrime(num) {
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i == 0)
      return false;
  }
  return true;
}

// Check all numbers for primality
let sum = 0;
for (let i = 2; i <= num; i++) {
  if (isPrime(i))
    sum += i;
}
return sum;
}

console.log(sumPrimes(10));
  **Your browser information:**

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

Challenge: Sum All Primes

Link to the challenge:

So the isPrime function simply tells us if a given number is prime or not. And the use of the Math.sqrt() is a little tricky to explain, but I’ll try.

Let’s start with an example: 36. Not prime, but for illustration I don’t want a prime. 36 is divisible by 2(*18), 3(*12), 4(*9) and 6(*6). By finding its factors under its square root, we find all its factors: 2,3,4,6,9,12,18.

Let’s try a different example: 41. Square root is six and some, so we know 7*7 falls outside of it. If it isn’t divisible by 2,3,4,5, or 6, it won’t be divisible by anything greater. As it isn’t evenly divisible by them, it’s prime.

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