第二题
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, ...
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
求Fibonacci数列中偶数的和。
前一段程序是我开始时做的,当时的想法很奇妙,结论也是对的。但是现在实在想不起为什么这么写了。当时的目的就是要把偶数的判断去掉。
这段程序必须在x比较大的时候才是正确的。
后一段就是中规中矩的写法了。
解决Fibonacci数列的办法很多,用数组,arr<<arr[arr.length-2] + arr。last也可以,像我这样用f1,f2也可以。
def Euler2(x)
sum = 2
f1 = 1
f2 = 1
while sum < x * 2
sum += f2 = f1 + f2
f1 = f2 - f1
end
puts sum/2, "\n"
sum = 2
f1 = 1
f2 = 2
while f2 < x
f2 = f1 + f2
f1 = f2 - f1
sum += f2 if f2 % 2 == 0
end
puts sum
end
#test
Euler2(4000000)