21 August 2010

Project Euler : Calculate the sum of all the primes below two million.

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.


Solution(in Ruby)
The solution to this problem involves the tricky implementation of prime number functionality. Rest is just a matter of programming.

def is_prime(n)
  return false if n <= 1
  2.upto(Math.sqrt(n).to_i) do |x|
    return false if n%x == 0
  end
  true
end
sum = 0
2.upto(2000000) do |num|
  x+=num if is_prime(num)
end
puts "Sum is #{sum}"

Hover here to see the solution

Cheers!
Bragaadeesh

No comments: