Friday, April 24, 2009

F# Problem 14

Euler problem 14 was probably one of the more complicated for me to figure out conceptually. I suppose I'm an FSL student (functional as a second language). Nevertheless, the solution was simpler than I first anticipated.

The solution entailed creating a function that, when unfolded, would complete the sequence specified in the problem. One issue I encountered while solving this was a simple overflow issue with my values. I had to change the basic type used to solve the problem from int to int64. The result can be calculated within a few seconds.


let seq x = 
let next x =
match x with
| 1L -> None
| _ ->
match x % 2L with
| 0L -> Some(x, x / 2L)
| _ -> Some(x, (3L * x) + 1L)

Seq.unfold next x


let s = Seq.map seq [1000000L .. -1L .. 500000L]


let result =
Seq.map (fun x -> (Seq.length x, Seq.hd x)) s
|> Seq.max_by (fun x -> fst x)
|> snd

let print = result |> printfn "%A"