Sum of Prime Numbers [Edabit]

Create a function that takes an array of numbers and returns the sum of all prime numbers in the array.

Examples

sumPrimes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ➞ 17

sumPrimes([2, 3, 4, 11, 20, 50, 71]) ➞ 87

sumPrimes([]) ➞ 0

Notes

  • Given numbers won’t exceed 101.
  • A prime number is a number which has exactly two divisors (1 and itself).

Solution:

function sumPrimes(arr) {
  let sol = 0;
  for (let num of arr) {
    if (isPrime(num)) {
      sol += num;
    }
  }
  return sol;
}

const isPrime = (num) => {
  if (num == 2 || num == 3) {
    return true;
  }
  if (num == 1) {
    return false;
  }
  for (let i = 2; i <= Math.sqrt(num); i++) {
    if (num % i == 0) {
      return false;
    }
  }
  return true;
};

Leave a comment