Wednesday, 4 December 2013

Project Euler Problem 2 - Solved

Q) 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.

Solution: Python
===============

db = {0:1, 1:1} def fib(x): try: return db[x] except KeyError: db[x] = fib(x-1) + fib(x-2) return db[x] def testfib(): x = 1 while max(db.values()) <= 4000000: x = x+1 fib(x) return sum([i for i in db.values() if not i%2]) print testfib()

No comments:

Post a Comment