Skip to content

Project Euler: Problem 2

by Tony on May 25th, 2011

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)

From → Code, Python

6 Comments
  1. Kevin Fletcher permalink

    Please include links to Project Euler problem in question.

  2. Mohammad 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.

    • This example was found in the python docs.

      • Mohammad 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.

  3. Mohammad permalink

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

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS

Switch to our mobile site