Thursday, August 11, 2011

Project Euler #2 in Ruby

Project Euler #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.

Here is my solution:

  1. one = 1
  2. two = 1
  3. sum = 0
  4. while (two <= 4_000_000)
  5.   temp = one
  6.   one = two
  7.   two = one + temp
  8.   if (two % 2 == 0)
  9.     sum += two
  10.   end
  11. end
  12. puts sum

You will notice the '_' symbol where the commas would be (or periods if you don't live in the States), for reference in keeping track of how many zeroes we have if we were writing '4,000,000' out by hand.  Coding up '4_000_000', is basically the same, the compiler will ignore the underscores.  It is just so we can keep track of how many zeroes there are. 

I wanted to illustrate something handy in this tutorial, called 'parallel assignment'.  Nothing earth shattering, but it could cut down on the number of times you have to press the enter and equals key.

Ruby allows you to assign variables to values, lined up one after the other, on a single line of code.  If you will notice we combined lines 1 through 3 above into a single line (1) below.  The same is true for lines 5 and 6 above into a single line 3 below.  Line 4 below is still on its own line as Ruby won't let you do arithmetic while doing parallel assignment. 

  1. one, two, sum = 1, 1, 0
  2. while (two <= 4_000_000)
  3.   temp, one = one, two
  4.   two = one + temp
  5.   if (two % 2 == 0)
  6.     sum += two
  7.   end
  8. end
  9. puts sum

This isn't the most clever way of solving this problem, but certainly the easiest to understand.  We simply do what the question asks for:  Add up each even term of the Fibonacci sequence below 4,000,000. 

No comments:

Post a Comment