红宝石挖掘工

Dig ruby with Pickaxe

ProjectEuler_Problem2

xavier posted @ 2009年8月16日 01:25 in ProjectEuler with tags projecteuler ruby , 1608 阅读

Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.

                  找出所有小于4百万的Fibonacci数列中所有奇数项的和

 

 

fib = Hash.new {|h,n| n < 2 ? h[n] = n : h[n] = h[n-1] + h[n-2] }
s, n = 0, 1
while fib[n] < 4_000_000
  s += fib[n] if fib[n] % 2 != 0
  n += 1
end

p s  #=> 4613732

 

其中用一个hash来生成fibonacci数列是很久以前从网上看到的,当时非常震惊,立马就记住了


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter