Books I Like

Sunday, November 22, 2009

Solving Project Euler Problem #10 in Ruby

Problem Statement :-

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

Find the sum of all the primes below two million.

Solution :-



require "mathn"
require "benchmark"
module Enumerable
def lazy_select
Enumerator.new do |yielder|
each do |obj|
yielder.yield(obj) if yield(obj)
end
end
end
end

p 5+((5..2000000).lazy_select {|v| (v%6 == 1 || v%6 ==5) && v.prime?}.take(2000000)).inject(0) {|s,v| s+=v}
#Benchmark.bm(12) { |b| b.report('Report:') {5+((5..2000000).lazy_select {|v| (v%6 == 1 || v%6 ==5) && v.prime?}.take(2000000)).inject(0) {|s,v| s+=v}} }

No comments:

Get at Amazon