Project Euler Problem 2: Fibonacci Sequence

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.

The key to this problem is to understand the Fibonacci sequence. If you can write down the sequence on paper for the first 2-3 iterations writing the code shouldn’t be too hard. As you see below I start with the first two terms at 0, and 1. I add them up store them in a variable, and check if it’s divisible by 2 (checking if it’s even), and if it is I add the result to the final solution.

def fib():
    answer = 0
    first = 0
    second = 1
    while(second < 4000000):
        temp = first
        first = second
        second = temp + first
        if second % 2 == 0:
            answer += second
    return answer

print fib()
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s