Friday, May 28, 2010

Learning F# with projecteuler.net

Wow, lot of fun with projecteuler.net !

Problem 1

[1..999] |> Seq.filter( fun x -> (x % 3 = 0 || x % 5 = 0)) |> Seq.sum

Problem 2

let fib max = 
    let rec fibo a b max = 
        if b>= max then a :: [] else a :: fibo b (a+b) max
    fibo 1 2 max

fib 4000000 |> Seq.filter(fun x -> (x % 2 = 0)) |> Seq.toList|> Seq.sum

Problem 3

open Microsoft.FSharp.Math 
open System.Collections.Generic
let maxPrime:int= (int) (System.Math.Sqrt((float)600851475143I))
let primes maxPrime = 
    let pr : bool array = Array.zeroCreate maxPrime
    let res = new List()
    for cur in 2 .. maxPrime/2 do
        if not pr.[cur] then for wr in cur+cur .. cur .. maxPrime-1 do pr.[wr] <- true
    for cur in 1 .. maxPrime-1 do
        if not pr.[cur] then res.Add(new bigint(cur))
    res

primes maxPrime |> 
    Seq.filter(fun x -> ((600851475143I % x) = 0I )) 
    |> Seq.map( fun x -> ((int)(x))) 
    |> Seq.max

No comments: