Project Euler: Problem 2

Right, here is my attempt at problem 2 of project euler.

Problem: http://projecteuler.net/index.php?section=problems&id=2

source: https://bitbucket.org/TWith2Sugars/project-euler/changeset/3ec9f237dbb9

def fib(n):
    evenSum, a, b = 0, 0, 1
    while a < n:
        a, b = b, a+b
        if b % 2 == 0:
		    evenSum += b

    return evenSum;

result = fib(4000000)
print(result)

Update:

Thanks to Mohammad’s advice the code has been update to avoid pointlessly assigning variables.

def fib(n):
    evenSum, a, b = 0, 1, 2
    while a < n:
        if b % 2 == 0:
		    evenSum += b
        a, b = b, a+b
    return evenSum;

result = fib(4000000)
print(result)

6 Comments

  • Kevin Fletcher
    May 28, 2011 - 9:18 pm | Permalink

    Please include links to Project Euler problem in question.

  • Mohammad
    June 5, 2011 - 3:38 pm | Permalink

    Short and elegant.
    I noticed that if a and b are switched to 1,2, you will get the wrong answer. Lines 5 and 6 should come before line 4.

    • June 5, 2011 - 7:46 pm | Permalink

      This example was found in the python docs.

      • Mohammad
        June 7, 2011 - 5:54 pm | Permalink

        If this is the one you are talking about, it doesn’t have the check for even numbers. By not writing it before line 4 you are ignoring the input values since you are changing the variables before testing. In the case of (0,1) it doesn’t matter, but for (1,2), it does.

  • Mohammad
    June 7, 2011 - 5:55 pm | Permalink

    The link I’m talking about – http://docs.python.org/tutorial/modules.html 🙂

    • June 7, 2011 - 6:28 pm | Permalink

      That’s the one (although I am actually using python 3.x)

  • Leave a Reply