bbschat 2008-1-18 23:39
关于斐波那契数列的题目
也就是这个网站的第2题
[url]http://projecteuler.net/index.php?section=problems&id=2[/url]
原文是
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 one million.
我理解是对斐波那契数列中小于 1000000 的值求和。
[code]
t = [1,2]
s = 3
while t.last < 1000000
x = t[t.size - 2] + t.last
s += x
t << x
end
s -= t.last
t.pop
p t
p s
[/code]
得到的斐波那契数列如下:
[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]
求和结果:2178307
但是网站告诉我结果不对。难道是我理解错误了?
5swords 2008-1-19 09:22
even-valued 是偶数啊, 你应该完成了吧
5swords 2008-1-19 21:05
要 是你觉得对题目理解有疑问,可以直接MESSAGE我,不用给R币。
呵呵,碰到客气的人,发财了。
jmouse 2008-3-1 16:18
插一脚,我的代码。
[code]
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"
end
#test
Euler2(4000000)
[/code]