Even Fibonacci Terms

Computer Science Level pending

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


The answer is 4613732.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Bill Bell
Oct 28, 2014

Alternative 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def fib ( ) :
    t0, t1 = 1, 2
    yield t0
    yield t1
    while True :
        t2 = t0 + t1
        t0, t1 = t1, t2
        yield t2

f = fib ( ) 
sum = 0
while True :
    term = f . next ( )
    if term <= 4000000 :
        if term % 2 == 0 :
            sum += term
    else :
        break
print sum

Alternative 2:

Get the terms from http://oeis.org/A000045. Copy and paste them into a list. Make the calculation using a list comprehension.

1
2
fs=[    0, 1, 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, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169]
sum([i for i in fs if i % 2==0 and i <=4000000])

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...