Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sum of All Primes

Status
Not open for further replies.

CrxC01

Technical User
Mar 25, 2021
5
CH
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;
}


hello,

can someone explain me please how is 2 added to sum, since 10 is divisible with 2 and after executing this line if (num % i == 0)
return false; is returning false?and is IsPrime si false 2 is not added to sum...

And how 4 and 5 and the rest of the numbers are checked if the for (let i = 2; i <= Math.sqrt(num); i++) Math.sqrt(10) is 3,16?
it means that is only checking 2 and 3...?


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top