Created
June 8, 2011 12:26
-
-
Save nagat01/1014320 to your computer and use it in GitHub Desktop.
F# : Project Euler 2 solution in 4 different ways
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Program | |
| open System | |
| let problem2 = // 4613732 | |
| let mutable n1,n2,sum=1,2,0 | |
| while n1<4000000 do | |
| if n1%2=0 then | |
| sum <- sum + n1 | |
| n2 <- n1+n2 | |
| n1 <- n2-n1 | |
| sum | |
| let problem2_2 = // 4613732 | |
| Seq.unfold(fun(n1,n2)-> Some(n1,(n2,n1+n2)) )(1,2) | |
| |> Seq.takeWhile((>)4000000) | |
| |> Seq.filter(fun n->n%2=0) | |
| |> Seq.sum | |
| #nowarn "40" | |
| let problem2_3 = | |
| let rec fib = | |
| seq{ | |
| yield! [1;2] | |
| yield! Seq.map2(+) fib (Seq.skip 1 fib) } | |
| fib | |
| |> Seq.filter(fun n->n%2=0) | |
| |> Seq.takeWhile((>)4000000) | |
| |> Seq.sum | |
| let problem2_4 = | |
| let rec fibList=function | |
| | n2 :: n1 :: _ as l when n2<4000000 -> f <| n1+n2 :: l | |
| | l -> l | |
| fibList [3;2;1] |> List.sum | |
| [<EntryPoint>] | |
| let main _ = | |
| printfn "%d" problem2 | |
| printfn "%d" problem2_2 | |
| printfn "%d" problem2_3 | |
| printfn "%A" problem2_4 | |
| Console.Read() |> ignore | |
| 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment