Project Euler第二题

15 篇文章 0 订阅
11 篇文章 0 订阅

题目:

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,前两个数出队,再进来两个数,依然是这种形式。于是就有了这个算法。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值