# [SPOILER] - Sum All Primes - how to make it more efficient

My code works in Codepen but fail to pass tests here - I suppose it is not efficient enough.
How can I make it simpler? Or should I change algorithm?

``````function sumPrimes(num) {
var sum = 0;
LoopOne :
for(var current = num % 2 == 0 ? num - 1 : num; current > 1; current -= 2){
for(var i = current - 1; i > 1; i--){
if(current % i === 0) continue LoopOne;
}
sum = sum + current;
}
console.log(sum+2);
return sum+2;
}
sumPrimes(977);
``````

thank you)

This was my solution:

``````function sumPrimes(num) {
let result = 0;
// iterate from 2 to num
for (let i = 2; i <= num; i++){
let count = 0;
// iterate from 1 to i, count instances of i % j === 0
for (let j = 1; j <= i; j++){
i % j === 0 ? count++ : '';
}
// if count === 2, sum that num to result
count === 2 ? result += i : '';
}
// return the sum of all primes
return result;
}

sumPrimes(977);

``````

While the previous solution works, the problem reads ‘The provided number may not be a primer’.
In that case, I would tweak the code to give feedback if the user inputs either a negative number, a floating point, 1 or 0;

``````function sumPrimes(num) {
if (num % parseInt(num) !== 0 || num < 2){
return 'Invalid, insert an integer greater than 1';
} else {
// result variable
let result = 0;
// iterate from 2 to num
for (let i = 2; i <= num; i++){
// iterate from 1 to i, count instances of i % j === 0
let count = 0;
for (let j = 1; j <= i; j++){
i % j === 0 ? count++ : '';
}
// if count === 2, sum that num to result
count === 2 ? result += i : '';
}
// return result
return result;
}
}
``````

Hope it helps, I wanted to upload it to the hints section because I think it’s pretty clear.

thank you for your reply, however, I’m interested why my code isn’t working.
I guess algorithm is not best.
I like you solution)

ok now it is working! I don’t understand it - I change nothing

now that is spooky,
oo btw the `[spoiler]` should have been put outside the triple backtick to work

``````let this = "be a an example code"
``````
1 Like

psyperl thank you!