Project Euler每帖一题(002)

题目:
引用

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.


开始写的代码是:
start = [1,2]
pointer = 0
num = 2
flag = True
while flag:
    add_num = start[pointer] + start[pointer+1]
    start.append(add_num)
    pointer += 1
    if add_num % 2 == 0:
        num += add_num
    flag = (start[pointer] + start[pointer+1] <= 4000000)
print num


后来看了别人写的,才发现只要两个数做交换就够了:
a = 1
b = 2
num = 2 #第一个偶数:2
flag = True
while flag:
    add_num = a + b
    a = b
    b = add_num
    if add_num % 2 == 0:
        num += add_num
    flag = ((a + b) <= 4000000)
print num


如果有更好的的解法,求交流~

你可能感兴趣的:(python)