I am trying to write an algorithm to calculate the sum of prime numbers less than or equal to a given number argument. Here is my code:
function sumPrimes(num) {
// populates the array with numbers uptp the given num
let prime = [], i = 2;
while (prime.indexOf(num) < 0){
prime.push(i)
i++;
}
// filters the array leaving only the prime numbers and sums all prime numbers
let result = prime
.filter(function (a){
if(a === 2 ||a === 3 || a === 5 || a === 7){
return a
} else {
return a % 2 > 0 && a % 3 > 0 && a % 5 > 0 && a % 7 > 0
}}).reduce((a,b) => a+b)
console.log(result)
return result
}
sumPrimes(977); //outputs 108789 instead of 73156
My filter function check if a given number divisible simultaneously by 2, 3, 5, 7 returns a remainder greater than zero if so such number is a prime number. However, when the supplied argument is 977, it falls apart and outputs the wrong sum. Can anyone figure out what is going on here?