题目:
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.
算法1:
#usr/bin/env python
UP_LIMIT = 4*(10**6)
result = 1L
temp = 0L
i = 1
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 2
return fibonacci(n-1) + fibonacci(n-2)
while True:
temp = fibonacci(i)
i += 1
if temp < UP_LIMIT:
result += temp
else:
break
while True:
i -= 1
temp = fibonacci(i)
if temp%2 != 0:
result -= temp
else:
break
result /= 2
print result
直接使用fibonacci函数算出每个小于4M的数,再减去结尾不是偶数的数,最后除以二,得出结果(ps:我运行的时候没有得出正确的结果,汗!,至于为什么我自己也不清楚,如果哪位大神路过,看了原因,不妨告诉小弟一声。)
这个算法基本上每个人都会,没有任何效率可言。算法2:
#usr/bin/env python
UP_LIMIT = 4*(10**6)
result = 1L
lst = [1,2,3]
while True:
if (lst[1]+lst[2]) < UP_LIMIT:
lst.append(lst[1]+lst[2])
result += lst.pop(0)
else:
break
for i in lst:
result += i
if i%2 ==0:
break
result = result/2
print result
这个算法有点改进,队列里只有三个数,下个fibonacci入队,第一个数出队并求和。
fibonacci函数中都是两个奇数一个偶数的顺序排列的,所以队列里的三个数,必定有一个是偶数。
再把偶数之前的数求和,除以2就得到结果。
结果:
4613732
别人的算法:
def calcE():
x = y = 1
sum = 0
while (sum < 1000000):
sum += (x + y)
x, y = x + 2 * y, 2 * x + 3 * y
return sum
很明显这个算法的效率要比我那个算法好的多,起初我也想过这样算,可是做算法的时候陷入死角了,没做出来。
这个算法是这样的:
把数列最前边加个1,形式变成奇数、奇数、偶数,一直循环下去,从数列中取出前五个数,就是x,y,x+y,x+2y,2*x+3*y,前两个数出队,再进来两个数,依然是这种形式。于是就有了这个算法。