Skip to content

Instantly share code, notes, and snippets.

@folz
Created March 3, 2011 06:21
Show Gist options
  • Save folz/852426 to your computer and use it in GitHub Desktop.
Save folz/852426 to your computer and use it in GitHub Desktop.
Project Euler problem #2
'''
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.
'''
from time import *
calcs = {}
def fib(n):
if n == 0:
return 1
if n == 1:
return 1
else:
try:
return calcs[n]
except:
calcs[n] = fib(n-1) + fib(n-2)
return calcs[n]
if __name__ == "__main__":
start = time()
i = 0
c = 0
x = fib(i)
while x < 4000000:
i += 1
x = fib(i)
if x % 2 == 0:
c += x
print(c, time() - start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment