Hello coders, need your help.
I’ve checked all existing topics about this challenge and it did’n help.
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);
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.