Here's problem #2 with F#. The question is the following:
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.
Below is the python solution:
def Fibonacci(): total = 0 lastValue = 1 value = 1 while value < 4000000: if value % 2 == 0: total += value tmpValue = value value = value + lastValue lastValue = tmpValue return total print Fibonacci()
It's a pretty straightforward solution. The code iterates through from 1 to 4 million and determines if the number is even and keeps track of the total.
Below is the F# solution:
let upperBound = 4000000 let fibSeq = Seq.unfold(fun (a,b) -> if a <= upperBound then Some (a, (b, a+b)) else None) (0, 1) let total = fibSeq |> Seq.filter(fun n -> n % 2 = 0) |> Seq.sum sprintf "%i" total
There are a few functions I'm using here, the unfold, takewhile, filter, and sum. Below are the signatures for all the functions:
Seq.unfold : ('State -> ('T * 'State) option) -> 'State -> seq<'T>
Seq.filter : ('T -> bool) -> seq<'T> -> seq<'T>
Seq.sum : seq<^T> -> ^T (requires ^T with static member (+) and ^T with static member Zero)
The unfold function creates the Fibonacci sequence while the (a <= upperBound) is true. Filter will remove any numbers that are not divisible by 2 and sum will add all the remaining numbers in the sequence.
Again, I prefer the F# solution since it's a bit cleaner and more legible.