Tell us what’s happening:
I understand that the helper function only returns a value of prime for sum to use. But is if(isPrime(i)) on line 18 referencing i of the helper function? I think I just don’t understand how for loops work…
The second question (which made complete sense up until now) is based on my iteration() function. A fundamental understanding of both referencing helper functions and for loops would really solidify my understanding of javascript
Your code so far
function sumPrimes(num) {
// Helper function to check primes
function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
//square rooting num so that each iteration of i, which is two, is balanced out by the square root(for example, sqrt of 10 is 3, so i is 6, 10 % 6 is 4, which returns true)?
if (num % i == 0)
//this returns false if the remainder of num based on the square root of i is a composite
return false;
}
return true;
}
// Check all numbers for prime
let sum = 0;
for (let i = 2; i <= num; i++) {
//we use 10 again, which means i = 20
if (isPrime(i))
//we then put in 20 into isPrime(20) which based on the for loop, returns true? then the answer is 21 if I pass in 10 as num? HALP
sum += i;
}
return sum;
}
console.log(sumPrimes(10))
function iteration(int){
let sumnum = 0;
for(let i = 2; i < int; i++)
{
sumnum += i
}
return sumnum;
}
console.log(iteration(4))
/*shouldn't it be 6 because the for loop only iterates 3 times (exluding the int value 4 itself because not <=) and thus sumnum is 3 iterations of i added together, and since i is 2 we return 6.
but console.log() returns 5? It gets even weirder if I increase i in iteration() to 3, and the console logs a lower number of 3. */
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36
.
Challenge: Sum All Primes
Link to the challenge: