Project Eueler: problem10
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
prime = [2] sum = 2 limit = 2000000 (3..limit).each do |x| flg = true prime.each do |y| if x % y == 0 flg = false ;break end end if flg == true prime.push(x) sum += x end end p "ans = #{sum}"
とやってみたが計算が終わらず断念。
require "mathn" module Enumerable def sum inject(0) {|a, n| a + n } end end prime = Prime.new p prime.sum
でもやっぱり遅い。
mathnのPrimeは遅いらしい。
以下を参考に、エラトステネスのふるいを使うとOKだった。