overfl0w
overfl0w

Reputation: 59

Adding all even fibonacci numbers

I am trying to add all even Fibonacci numbers up to 4000000. I have successfully outputted all Fibonacci numbers up to 4000000, but adding all the even ones is becoming a problem for me. So far this is what I tried:

fibonacci = [1, 2]
i = 0
while fibonacci[-1] < 4000000:
    fib = fibonacci[-1] + fibonacci[-2]
    fibonacci.append(fib)
    i += 1
del fibonacci[-1]

result = 0
for x in fibonacci:
    if fibonacci[x] % 2 == 0:
        result += fibonacci[x]
print(result)

It outputs an error:

IndexError: list index out of range

Upvotes: 2

Views: 224

Answers (3)

Victor
Victor

Reputation: 1

That's how I wrote as a beginner.

#By considering the terms in the Fibonacci sequence whose values do 
#not exceed four million, 
#find the sum of the even-valued terms.
cache = {}
def fib(n):
    if n < 3:
        return 1
    elif n in cache:
        return cache[n]
    else:
        value =  fib(n - 1) + fib(n - 2)
        cache[n] = value
        return value
tot = 0
for n in range(1, 34):
    if fib(n) % 2 == 0:
        tot += fib(n)
        print(n, ':', fib(n))
print(tot)

Upvotes: 0

Yury
Yury

Reputation: 1

A small compilation of previous answers

fibonacci = [0, 1]
while fibonacci[-1] + fibonacci[-2] < 4000000:
    fibonacci.append(fibonacci[-1] + fibonacci[-2])

print(sum(x for x in fibonacci if x % 2 == 0))

Upvotes: 0

ggorlen
ggorlen

Reputation: 56965

In the lines:

for x in fibonacci:
    if fibonacci[x] % 2 == 0:
        result += fibonacci[x]

x is actually the Fibonacci number itself, not an index, and is guaranteed to be outside of the bounds of the fibonacci list. If the code was for x in range(len(fibonacci)):, this would yield the indexes as x.

Change it to:

for x in fibonacci:
    if x % 2 == 0:
        result += x

or better yet, use a list comprehension:

result = sum(x for x in fibonacci if x % 2 == 0)
print(result)

Furthermore, instead of building an entire list, you could accumulate the sum on the spot as you generate the Fibonacci numbers, which is much more memory-efficient:

def even_fib_sum(n):
    total = 0
    a = 0
    b = 1

    while a < n:
        if a % 2 == 0:
            total += a 

        a, b = a + b, a

    return total

if __name__ == "__main__":
    print(even_fib_sum(55))

Or, even better, you can use a generator and drop even, since fib is more generally reusable:

def fib(n):
    a = 0
    b = 1

    while a < n:
        yield a
        a, b = a + b, a

if __name__ == "__main__":
    print(sum(x for x in fib(4000000) if x % 2 == 0))

Note that the Fibonacci series usually begins with 0, 1, 1, 2, 3, 5... rather than 1, 2, 3, 5... but you can adjust this as necessary, along with whether you want to iterate inclusive of n or not.

Upvotes: 3

Related Questions