Skip to content

Instantly share code, notes, and snippets.

@nagat01
Created June 8, 2011 12:26
Show Gist options
  • Select an option

  • Save nagat01/1014320 to your computer and use it in GitHub Desktop.

Select an option

Save nagat01/1014320 to your computer and use it in GitHub Desktop.
F# : Project Euler 2 solution in 4 different ways
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