Sunday, May 30, 2010

Learning F# with Project Euler - day 2

Problem 4

open Microsoft.FSharp.Core.Operators
let findpalindrome xs ys =
    let separate s p = (s % (pown 10 (p+1))) - (s % (pown 10 p))
    let shiftl s p o = (separate s p) / (pown 10 (p-o))
    let shiftr s p o = (separate s p) * (pown 10 (o-p))
    let flip f = shiftl f 5 0 + shiftl f 4 1 + shiftl f 3 2 + shiftr f 2 3 + shiftr f 1 4 + shiftr f 0 5
    let findi xs y = xs |> Seq.filter( fun x -> (((x*y) = flip (x*y)) && (separate (x*y) 0 <> 0) ) ) |> Seq.map(fun x -> (x*y,x))
    ys |> Seq.collect(fun y -> (findi xs y)) |> Seq.maxBy(fun t -> fst(t))

findpalindrome [100..999][100..999]

Problem 5

let test = 
    let max = (primes 20 |> Seq.reduce(fun a c -> a*c))*8L*3L
    [1L..20L] |> Seq.filter(fun x -> (max % x) <> 0L)

Problem 6

let diff xs = 
    let sumsq = xs |> Seq.reduce(fun c a -> (a*a)+c)
    let sum = (xs |> Seq.reduce(fun c a -> (a+c)))
    let sqsum  = sum*sum
    sqsum  - sumsq

diff [1..100]

Problem 7

open Microsoft.FSharp.Core.Operators
let primesnth nthprime = 
    let maxPrime = 300000
    let pr : bool array = Array.zeroCreate maxPrime
    let mutable res = 0
    let mutable nth = 0
    let mutable cur=2
    while (nth < nthprime) do
        if not pr.[cur] then
            for wr in cur+cur .. cur .. maxPrime-1 do pr.[wr] <- true
            res <- cur
            nth <- nth + 1 
        cur <- cur + 1
    res

primesnth 10001

No comments: