Posts

Showing posts from February, 2011

Project Euler - Problem #36

Description
The decimal number, 585 = 1001001001 (binary), is palindromic in both bases.Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.(Please note that the palindromic number, in either base, may not include leading zeros.)
Solution (Improved)

let isPalindromicBase2 (n:int) =
     let forward = System.Convert.ToString(n,2) |> Seq.map (fun c -> int c - int '0') |> Seq.toArray
     let rev = Array.rev forward
     if forward = rev then
          true
     else
         false

let reverse (s:string) = new string(s |> Seq.toArray |> Array.rev)

let getPalindromesBase10 =
     let base10Array = [|1..1000000|] |> Array.filter (fun x -> string x = reverse(string x))
     let base02Array = base10Array |> Array.filter (fun x -> isPalindromicBase2  x)
     Array.sum base02Array

Solution (Original)
let reverseToBinaryList (n:int) =
System.Convert.ToString(n,2)      |> Seq.map (fun c -> int c - int '0')
    …

Project Euler - Problem 34

Description
145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.Find the sum of all numbers which are equal to the sum of the factorial of their digits.Note: as 1! = 1 and 2! = 2 are not sums they are not included.
Solution

let rec factorial n acc =
     if n <= 1 then
          acc
     else
          let newAcc = n * acc
          factorial (n-1) newAcc

let sumStr num =
     let arrStr = num.ToString()
     let len = String.length arrStr
     let arrNum = Array.create len 0
     for i=0 to len-1 do
          let numTemp = System.Convert.ToInt32(arrStr.Chars(i).ToString())
          arrNum.[i] <- factorial numTemp 1
     Array.sum arrNum

let sumTest = [3..99999]
     |> Array.map (fun x -> if sumStr x = x then x else 0)
     |> Array.sum