Euler Problem 10 -Summation of primes

Summation of primes

Problem 10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17
Find the sum of all the primes below two million.

In this problem we are trying to find sum of all the prime numbers below a certain number. As in given example, the prime numbers below 10 are 2, 3, 5, and 7 and when we sum it the answer comes out ot be 17. The logic which I tried to apply was to generate an odd-valued sequence from 3 to that number and check if the number is prime of not and finally, sum those numbers which are prime.

To find out if a number is prime or not, I am using the is_prime function which is wrote in for example 3 previously. The is_prime function returns TRUE or FALSE, if a particular number is prime or not. We generate a sequence from 3 to the number and increment it by 2. Then using sapply we call is_prime function on every number. This would return a vector of logical values based on if a number is prime of not. We subset only those numbers which return TRUE and sum oer it. Finally, we add 2 in the final answer as 2 is the only even prime number and we haven’t considered it in the sequence.

getSumOfPrimes = function(x) {
additionSum = 0
numSeq = seq(3, x,by = 2)
additionSum = sum(numSeq[sapply(numSeq, is_prime)])
return(additionSum + 2)

Now, to test,

#[1] 17
#[1] 142913828922

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s