Even Fibonacci numbers

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 solution is straightforward. Create a function taking an integer n which creates a classic Fibonacci sequence,
F_n = F_{n-1} + F_{n-2}
where $F_0 = 0$ and $F_1 = 1$.

With an if instruction, add only the even numbers of this sequence. Finally return the result.

Of course, any suggestions or improvements are always welcome in the comments.

def sum_even_fib(n): 
    sumfib = 0
    a, b = 0, 1
    while b < n:
        a, b = b, a + b
        if b % 2 == 0:
            sumfib = sumfib + b 
    return sumfib

Go back to the list of problems.



Leave a Reply to Ngoc Tran Cancel reply