Project Euler N° 2, in Ruby
http://projecteuler.net/index.php?section=problems&id=2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
def fib(limit)
f_n_1 = 1
f_n_2 = 1
curr = [1,1]
while (f_n_1 + f_n_2) <= limit
curr.push(f_n_1 + f_n_2)
f_n_2 = f_n_1
f_n_1 = curr.last
end
return curr
end
Limit = 4000000
allFib = fib(Limit)
iter = allFib.size/3
puts allFib
puts iter
sum = 0
for i in 0..iter
if i*3 + 2 > allFib.size
break
end
sum += allFib[i*3 + 2]
end
puts sum
<< Home