Sum all primes...Challenge

Hey, everything went nearly smooth, till last few challenges im dealing with.

function sumPrimes(num) {
  var numbers = [];

 
    for (var i = 2; i <= num; i++) {
      if (isPrimeNumber(i)) {
        
        numbers.push(i);
      }
    }

 return numbers.reduce(function(a, b) {
  return a + b;

});
    
  }

    function isPrimeNumber(num) { 

    for (var x = 2; x < num; x++) {
    if(num % x === 0) {

     return false;
    }


  }

  return true;
}


sumPrimes(10);

Can anyone PLEASE explain the logic behind this? how those two function match each other? how the loop passes results…I really dont get this one

For the IsPrime function
The fundamental thing is

if(num % x === 0) 

this checks if the paramter num is evenly divisible by x. I.e. if the remainder when dividing is 0. If this is the case then by the definition of a prime number it can’t be a prime number.

The loop checks if this condition is true for any number from 2 to num-1.
If no such number divides the argument num, then it is a prime.

N.b. that this is a horribly inefficient prime checker.
https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes is much much faster.

okay, so we have a num = 10.

if(10 % 2 === 0) remainder = 2…So this is true… What now? this 2 goes to the first function like this:
if(isPrimeNumber(i) === if(2(2)…This is the same? so now the 2 goes to numbers… And now we have

if(10 % 3 === 0) remained = 1…
if(isPrimerNumber(3) === if(1(3)…Please explain a bit further of hove those functions match and which number they pass each other…I understand the rest

Ok, sumPrimes(10)

First thing that happens is the for loop
for(var i = 2; i <= 10; i++)

So inside this loop the calls are
isPrime(2)
isPrime(3)
isPrime(4)
isPrime(5)
isPrime(6)
isPrime(7)
isPrime(8)
isPrime(9)
isPrime(10)

isPrime(2) results in the for loop
for(var x = 2; x < 2 x++) {
} i.e. it never runs
and thus isPrime will return true.

Therefore 2 will be pushed to the array numbers

isPrime(3)
will result in the prime
for(var x=2; x<3; x++) {

}
so it will check if 3 is divisible by 2, which it isn’t (the remainder is 1), therefore isPrime(3) will return true and 3 will be pushed (added) to the array numbers.

isPrime(4) results in the for loop
for(var x=2; x <4;x++) {
}
i.e it will check if 4 is divisible by 2 or 3.
Since 4 is divisible by 2 (remainder 0) the function will return false, and 4 will not be pushed to the array numbers.

This will continue on.

1 Like

Thank you very much.