As promised in my tweet, I am doing some of ProjectEuler now. I first started it some time ago, doing problem #1 using Scheme, but now I’m going through them, in order of “difficulty” (the more people who have finished, the easier) In various programming languages. For today I have my solution to problem #2 in Ruby.
Find the sum of all the even-valued terms in the sequence which do not exceed four million. Sounds simple enough, right? Well it is.
At the time of my tweet, I had the following solution, it was on the right track, but it was ever so slightly off.
counter = 0 fibo = 1 fibo2 = 1 while (fibo + fibo2) < 4000000 if (fibo2 % 2) == 0 counter += fibo2 end fibo2 += fibo fibo = fibo2 - fibo end print counter
So I decided to first write out plainly a function that would plainly compute fibonacci
def fib(a,b) c = b d = a + b return c,d end
So when I did it for getting the answer I ended up using that function, with the following code for execution:
counter,num1,num2 = 0,1,1 32.times do |i| num1,num2 = fib(num1,num2) if num2%2 == 0 counter += num2 end end puts counter
Which admittedly isn’t fair, since you have to know that the 32nd Fibonacci is the last one below 4,000,000.
But this got me thinking, and I started cutting and shortening, cutting and shortening until I was able to reduce it quite a bit. I took out the function definition, and left that to a single line of logic, as well as compounded it so it would calculate three at a time, since every third number in the Fibonacci sequence is even. The end result:
counter, a, b = 0,0,1 while b < 4000000 do a, b = a+2*b, a+2*b, 2*a+3*b counter += a end puts counter
I’m fairly certain I can cut it down some more, but I feel like I’ve already done a fair job of it so far, so I will move on to either implementing this in another language, or Euler #6.