Will Clausen's Website

Categories
WCW

Solution: Project Euler Problem 2

The problem:

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

My solution (in python):


# Author: Will Clausen
#
# Date: Jan 6, 2013
#
# This program will solve problem 2 in Project
# Euler.

# This function generates the fibonacci numbers
# under 4,000,000, sums the even ones, and returns
# the sum. Simple.
def problem2():
	f1 = 1
	f2 = 2
	fn = 0
	sum = 2

	while fn < 4000000:
		fn = f1 + f2
		f1 = f2
		f2 = fn
		if fn % 2 == 0:
			sum += fn

	return sum

Leave a Reply

Your email address will not be published. Required fields are marked *