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

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