I am stuck in finding the solution for a larger input, like the one mentioned below, can someone please help me with this,
function sumPrimes(num) {
if(num <=1)
return 0;
var sum = 0;
for(var i=2; i<=num ;i++){
if(isPrime(i)){
sum = sum + i;
console.log(sum);
}
}
return sum;
}
function isPrime(num){
for (var i=2 ;i<=Math.floor(Math.sqrt(num)); i++){
if(num % i == 0)
return false;
}
return true;
}
sumPrimes(977);
**Your browser information:**
User Agent is: <code>Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36</code>.
**Link to the challenge:**
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/
Your isPrime
function could be made faster by hoisting the condition out of the loop, since it’s re-evaluated on every pass
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++) {
... etc
This is the first properly challenging task, the main thing to change here is your algorithm to get a better time complexity
The problem of generating primes is a very famous one, so I’d recommend looking into well known much more performant solutions to it
My personal go-to when I have some reason to generate primes is the Sieve of Eratosthenes, though there are reasons this one isn’t the best as well (the space complexity unless handled could be a problem for much larger n
)
After you’ve understood and implemented that or another algorithm, if you want to optimise it a bit more consider looking up wheel optimization for the sieve