I'm currently working on creating an algorithm to compute the sum of prime numbers that are less than or equal to a specified number. Below is my attempt:
function calculatePrimeSum(num) {
// initialize an array with numbers up to the given num
let prime = [], i = 2;
while (prime.indexOf(num) < 0){
prime.push(i)
i++;
}
// filter the array to only keep prime numbers and then sum them up
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
}
calculatePrimeSum(977); //displays 108789 instead of 73156
In my filtering function, I check whether a number can be divided evenly by 2, 3, 5, or 7. If it leaves a remainder greater than zero, it's identified as a prime number. However, there seems to be an issue when the input is 977, resulting in an incorrect sum. Is there anyone who can identify what's causing this problem?