Project Euler Problem 2
September 24th, 2008
Problem 2 was another easy one.
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.
I brute forced it again, with a bit of optimisation.
We only need to add the even Fibonacci numbers, and if you look closely at the example above you might notice a pattern.
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144
An even number shows up every 3 numbers. So instead of calculating every number in the sequence below 4,000,000 and then test if it’s even, we can calculate every third number and add it straight onto the total. Here is what I came up with.
sum = 0 prev = 1 current = 2 while current < 4000000: sum = sum + current n = current current += 2 * (current + prev) prev += 2 * n print current print sum
For fun I also did it in 4 lines. This way is very inefficient, but it is small.
a = [1, 2] while a[len(a) - 1] < 4000000: a.append(a[len(a) - 1] + a[len(a) - 2]) print sum(filter(lambda x: x % 2 == 0, a))
Can anyone think of a shorter and/or more efficient way?
Project Euler Problem 1
September 24th, 2008
Problem 1 is extremely simple:
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.
I chose to just brute force it. I looped through numbers 1 - 999, checked if it was a multiple of 3 or 5 and if it was added it onto the total.
sum = 0 for i in range(1, 1000): if i % 3 == 0 or i % 5 == 0: sum = sum + i print sum
After a bit of editing I was able to get it onto 1 line:
print sum(filter(lambda x: x % 3 == 0 or x % 5 == 0, range(1,1000)))
Not the most efficient solution, but it works.