Tuesday, March 23, 2010

Project Euler Problem 2

In my last post I talked about how I've been using the Project Euler problems as a sort of Code Kata.  Thanks to @rickasaurus and @calvinb for providing great feedback/comments on that solution!

Problem 2 is below:

Problem 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, ...  Find the sum of all the even-valued terms in the sequence which do not exceed four million.

Tests:

```module Problem2Tests

open NUnit.Framework

[<TestFixture>]
type Problem2__When_finding_sum_of_even_valued_terms_in_the_fibonacci_sequence_up_to_89 () =
[<Test>]
member this.should_return_sum_of_44 () =
let result = Problem2.FindSum 89
Assert.AreEqual(44, result)

[<TestFixture>]
type Problem2__When_finding_sum_of_even_valued_terms_in_the_fibonacci_sequence_below_4_million () =
[<Test>]
member this.should_return_sum_of_4613732 () =
let result = Problem2.FindSum 4000000
Assert.AreEqual(4613732, result)
```
Code:

```module Problem2

let FindSum max =
let rec getFibonacciSumForEvens lastValue currentValue accumulator =
match lastValue + currentValue with
| sum when sum >= max -> accumulator
| sum when sum % 2 = 0 ->
getFibonacciSumForEvens currentValue sum (accumulator + sum)
| sum -> getFibonacciSumForEvens currentValue sum accumulator
getFibonacciSumForEvens 0 1 0
```