The problem that I found is in the advanced code solution. Inside the while loop. Instead check all dividers from 2 up to the square root of the given number “n” (as the theorem says), the code checks from n-1 until the square root n. And that has non sense, is less efficient (although seems works fine btw) and doesn’t match with the given code explanation in the guide.
PS: That part has also an indentation problem at the if conditional that makes the code less readable especially for a new learner like me.
Here is the original code: Guide Intermediate Algorithm Scripting: Sum All Primes
And here is my code proposal:
// step 1
let arr = Array.from({length: num+1}, (v, k) => k).slice(2);
// step 2
let onlyPrimes = arr.filter( (n) => {
let m = 2;
while (m > 1 && m <= Math.sqrt(n)) {
if ((n % m) === 0) {
return false;
}
m++;
}
return true;
});
// step 3
return onlyPrimes.reduce((a,b) => a+b);
}
console.log(sumPrimes(977));
As you can see my code inside the filter
method is different, has sense and match with the explanation given below.
So, How can I change the solution in the guide?
Many thanks.