Skip to content

Instantly share code, notes, and snippets.

@PEZ
Created January 14, 2009 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PEZ/47046 to your computer and use it in GitHub Desktop.
Save PEZ/47046 to your computer and use it in GitHub Desktop.
Project Euler Problem 2, some Python solutions
"""Sum of all even fibonacci numbers below 4000000
http://projecteuler.net/index.php?section=problems&id=2"""
#Brute force
def fibs_up_to(t, a=1, b=2):
while a < t:
yield a
a, b = b, a + b
sum(n for n in fibs_up_to(4000000) if n % 2 == 0)
#Only generating even fibs (every third)
def even_fibs_up_to(t):
a, b = 2, 3
while a < t:
yield a
a, b = a + 2 * b, 2 * a + 3 * b
sum(n for n in even_fibs_up_to(4000000))
#Only deal with the even fibs
def even_fibs_up_to(t):
a, b = 2, 8
while a < t:
yield a
a, b = b, a + 4 * b
sum(n for n in even_fibs_up_to(4000000))
#Golden ratio used for generating even fibs
def even_fibs_up_to(t):
phi = (1 + sqrt(5)) / 2
phi3 = phi ** 3
a = 2
while a < t:
yield a
a = round(a * phi3)
sum(n for n in even_fibs_up_to(4000000))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment