Jotting down stuffs
Project Euler Problem 12 – First time F# version
This is my first time doing F#. Also my first time doing functional programming at all. The F# code is based on the Brute-Force Method 3 that I came up with. Only managed to get about 3960 ms, that’s about 10 times the execution time of my C# code. I don’t think F# is meant to be slow, so probably it’s me not doing it the right way.
Here’s my first F# code:
open System
open System.Diagnostics
let stopwatch = Stopwatch.StartNew()
let triangleNumberSeq =
Seq.unfold
(fun (number, triangleNumber) ->
Some (triangleNumber, (number+1, triangleNumber+number+1)))
(1, 1)
let inline divide (number: int) (divisor: int) =
let quotient = number / divisor
let modulus = number % divisor
(quotient, modulus)
let inline divideSeq n =
let divideN = divide n
Seq.unfold
(fun divisor ->
match divideN divisor with
| (quotient, modulus) when divisor <= quotient ->
Some ((divisor, quotient, modulus), divisor+1)
| _ -> None)
1
|> Seq.filter (fun (_, _, modulus) -> modulus = 0)
let countFactor n =
Seq.fold
(fun count divideResult ->
match divideResult with
| (divisor, quotient, _) when divisor < quotient -> count+2
| _ -> count+1)
0 (divideSeq n)
let answer =
Seq.find
(fun triangleNumber -> countFactor triangleNumber > 500)
triangleNumberSeq
stopwatch.Stop()
printfn "Answer: %d" answer
printfn "Elapsed: %d ms" stopwatch.ElapsedMilliseconds
Console.ReadKey(true) |> ignore
I will be really grateful if anyone can tell me any tips on improving my F# code. Nevertheless, coming up next, the PLINQ version.
| Print article | This entry was posted by Amry on March 19, 2010 at 10:53 pm, and is filed under Project Euler. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |