Wednesday, September 17, 2008

Problem 2: Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million


'''
Problem 2
19 October 2001

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, ...

Find the sum of all the even-valued terms in the sequence which do not
exceed four million.
Solution: Stephen C. Murphy, September 17, 2008
I had just seen a fibonacci function in the Python Primer so I just modified
that function slightly to return a list. My original solution didn't include
a list comprehension, but now I'm a bit addicted to them so I couldn't resist.
'''
def fib(n):
soln = []
a, b = 0, 1
while b < n:
soln.append(b)
a, b = b, a+b
return soln

print sum([i for i in fib(4000001) if i % 2 == 0])

Monday, September 15, 2008

Problem 1: Add all the natural numbers below one thousand that are multiples of 3 or 5

I didn't save my first few Project Euler solutions, so I have recreated this one below. Look carefully, it's only one line.

'''
Problem 1
05 October 2001

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.
Solution: Stephen C. Murphy, September 15, 2008
I had to go back and do this because I didn't save my original solution.
'''
print sum([i for i in xrange(1, 1000) if i % 5 == 0 or i % 3 == 0])