project_euler/10.rb
Code:
# Project Euler Problem 10: Summation of Primes
# https://projecteuler.net/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.
def sieve(max)
primes = (0..max).to_a
primes[0] = primes[1] = nil
counter = 0
primes.each do |prime|
next unless prime
break if prime ** 2 > max
counter += 1
(prime ** 2).step(max, prime) { |m| primes[m] = nil }
end
return primes.compact
end
def solve(n)
return sieve(n).sum
end
puts solve(10)
puts solve(2_000_000)
Output:
17
142913828922