Tell us what’s happening:
Hello guys,
I should find the sum of all prime numbers that are less than or equal to num. I came up with solution but I do not know why it does not work, can anyone help me? (I know my approach is not best(It works when “num” is less than 90 ))
Your code so far
function sumPrimes(num) {
let sum = null
let array = []
for( let i = 2 ; i <= num ; i++ ){
for(let j = 1; j <= i; j++){
if( j !== 1 ){
if( i !== j ){
if(i % j === 0 ){
array.push(i)
i++
}
}
}
}
}
for(let k = 2 ; k <= num ;k++){
if(array.indexOf(k) === -1){
sum += k
}
}
return sum;
}
sumPrimes(977);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Sum All Primes
Link to the challenge: