Hsabes

Posted on

# Ruby Code Challenge: Sum of all primes within an array

A prime number is a number that is only divisible by itself and 1. Today I'll be walking through a fundamental algorithm problem you may see in coding assessments: Finding all the prime numbers in an array, and generating their sum.

## Input

``````arr = [2, 5, 10, 12, 7, 2, 11, 4]
``````

## Output

``````--> 27
``````

## Find a single prime

Before you can find a multitude of primes within an array, we need the capability of determining whether or not a single integer is a prime number.

``````num = 5

def is_prime?(num)
end
``````

First step is to create an array of values we will be dividing our integer by. Since we don't need to check 1 and the integer we're testing, we can leave those out of our range.

``````def is_prime?(num)
(2...num).to_a
end

--> [2, 3, 4]

``````

We've created an array of values from 2 to the number we are testing, now we need to select the values that DO divide into our integer in question.

``````def is_prime?(num)
(2...num).to_a.select{ |divisor| num % divisor === 0 }
end

--> []
``````

If our integer truly is a prime number, our return should be an empty array. If it isn't prime, it will be filled with a bunch of values that divide into the non-prime integer. Lastly, all we have to do is evaluate presence of values inside the array to determine whether or not we have a prime number.

``````def is_prime?(num)
(2...num).to_a.select{ |divisor| num % divisor === 0 }.length === 0 ? num : false
end

--> true
``````

However, since this is only the first step, we will need the actual number instead of just a boolean telling us it's true. If the method we've written evaluates to true (meaning it's a prime number), we'll need that value for later.

## Find multiple primes

``````def find_and_sum_primes(arr)
end
``````

This process is very similar to the previous one, but the method we've already written is going to do all the work for us. First, create an empty array inside the method. This will soon house all the prime values in the array being passed as an argument. Then iterate through the input array using select:

``````def find_and_sum_primes(arr)
primes = []
arr.select{ |num| # find if num is prime }
end
``````

Thankfully, we can just call the method that we've already written to determine if the specific value being selected is in fact prime. Once we have a prime number, push it to our primes array and sum the values

``````def find_and_sum_primes(arr)
primes = []
arr.select{ |num|
if (is_prime?(num))
primes << num
end
}
primes.sum
end

--> 27
``````