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:
- one = 1
- two = 1
- sum = 0
- while (two <= 4_000_000)
- temp = one
- one = two
- two = one + temp
- if (two % 2 == 0)
- sum += two
- end
- end
- 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.
- one, two, sum = 1, 1, 0
- while (two <= 4_000_000)
- temp, one = one, two
- two = one + temp
- if (two % 2 == 0)
- sum += two
- end
- end
- 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