Project Euler第二題

題目:

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,前兩個數出隊,再進來兩個數,依然是這種形式。於是就有了這個算法。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章