DEV Community

Mark Harless
Mark Harless

Posted on

Sum All Primes

A prime number is a whole number greater than 1 with exactly two divisors: 1 and itself. For example, 2 is a prime number because it is only divisible by 1 and 2. In contrast, 4 is not prime since it is divisible by 1, 2 and 4.

Rewrite sumPrimes so it returns the sum of all prime numbers that are less than or equal to num.

Sometimes I forget not everything needs to be solved within one block of code. If your function tries to solve more than one problem, you should consider divvying up its tasks into other functions.

This problem is actually asking us to do two things: check if the number is prime and add up all the primes numbers up to num. We can do this by using two functions. The first one is to check if the number is prime. It simply returns a boolean of true or false:

const isPrime = num => {
  for (var i = 2; i < num; i++) {
    if (num % i === 0) return false
  }
  return true;
}
Enter fullscreen mode Exit fullscreen mode

isPrime() takes num as an argument. It will then run a for loop starting at 2 (because we already know 1 is a prime number). If at any point during our iteration num is divisible by i, we will return false and the function will end there. Otherwise, the number is a prime number and we return true.

This function does exactly what is asked of it: check to see if num is a prime number. It doesn't do any more or any less, however, we still have another function to write. We need to add the sum of all the prime numbers that are less than or equal to num.

const sumPrimes = num => {
  let primes = []

  for (let i = num; i != 1; i--) {
    if (isPrime(i)) primes.push(i);
  }
  return primes.reduce((acc, curr) => acc + curr)
}
Enter fullscreen mode Exit fullscreen mode

You can see in this function we are using isPrime() to check if the number, well, is prime. If I were to have combined both of these functions into one it would have been pretty messy.

So, sumPrimes takes in num, then it creates an empty array which we will use to store our prime numbers. A for loop is started but if you look closely, i is instantiated to num and from there we go down until i is equal to 0. At this point the loop will end. Inside the loop we are simply checking if num is prime. If it is we add it to our array. If it isn't we do nothing and keep iterating. Our return statement looks fancy schmancy using the reduce method but I only did that to make it look impressive. All it's doing is adding up all of our primes and returning it to us. And that's it!

Like I stated in the first paragraph of this blog post, it's important to know what a problem is asking of you. If you can read between the lines and notice it's wanting you to do more than just one thing, consider if splitting it up into separate functions would be better.

Top comments (0)