Search

Categories

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Send mail to the author(s) E-mail

# Wednesday, 07 October 2015
( c# | Euler | Euler Functional | F# )

https://projecteuler.net/archives  is a fantastic list of puzzles which are solvable by programming.

I find them excellent for exploring into a language.

https://github.com/djhmateer/Euler

Strategy is to explore F#, then see how in C# it can be written

Problem1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

F#

// Solution5 - List.filter let total' = [1..999] // filter on a function (predicate) |> List.filter(fun i -> i % 5 = 0 || i % 3 = 0) |> List.sum printfn "result %i" total

C#

// Solution 1 - Iterative approach int sum = 0; for (int i = 1; i < 1000; i++) { if (i % 3 == 0 || i % 5 == 0) sum += i; } Console.WriteLine(sum); // Solution 2 - F# inspired solution - using Enumerable var result = Enumerable.Range(1, 999).Where(x => x % 3 == 0 || x % 5 == 0).Sum(); Console.WriteLine(result);
| | # 

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

F# Iterative

module Euler2 // using a top level function as debugging experience better let Solution1() = // iterative.. a b temp let mutable a = 1 let mutable b = 1 let mutable sum = 0 while b <= 4000000 do if (b%2=0) then sum <- sum + b let temp = a + b a <- b b <- temp printfn "%A" sum // 4,613,732 Solution1()

F# Functional

//http://factormystic.net/blog/project-euler-in-fsharp-problem-2 // Some - given b.. if it is Some-thing.. return a Tuple with // first = b // second = a+b let fibGen (a,b) = Some(b, (b, a + b)) let fib = Seq.unfold(fibGen) (1,1) let results = fib |> Seq.takeWhile (fun x -> x < 4000000) for result in results do printfn "%A" result let sum = results |> Seq.filter(fun x -> x%2 = 0) |> Seq.sum printfn "%i" sum


C# Functional

//http://basildoncoder.com/blog/project-euler-problems-1-and-2.html static void Main() { var result = Fibs().TakeWhile(f => f < 4000000).Where(f => f % 2 == 0).Sum(); Console.WriteLine(result); } static IEnumerable<long> Fibs() { long a = 0, b = 1; while (true) { yield return b; b = a + b; a = b - a; } }

Very interesting implementation on an infinite list in C#
| | # 
# Thursday, 15 August 2013
( Euler | F# )
let isPyTriplet a b c =
    (a*a) + (b*b) = (c*c)

for a in 1..999 do
    for b in 1..999 do
        let c = 1000-a-b
        if isPyTriplet a b c then
            if(a+b+c = 1000) then
                printfn "%i %i %i" a b c

[<Fact>]
let isPyTriplet_given345_true() = Assert.True(isPyTriplet 3 4 5)

[<Fact>]
let isPyTriplet_given346_() = Assert.False(isPyTriplet 3 4 6)

[<Fact>]
let isPyTriplet_given123_() = Assert.False(isPyTriplet 1 2 3)

Imperative style

// Make a sequence of tuples
let tripletsSum1000 =
                        seq {
                        for a in 1 .. 333 do
                            for b in a + 1 .. 499 do
                                let c = 1000 - b - a
                                if a < b && b < c then
                                     yield (a,b,c)
                         }

// Find from this sequence one that is Pythagorean and return the product
let problem009 =
     tripletsSum1000
     |> Seq.find (fun (a,b,c) -> a * a + b * b = c * c)
     |> fun (a,b,c) -> a*b*c

printfn "%A" problem009

http://infsharpmajor.wordpress.com/2011/10/12/project-euler-problem-9/

| | # 
# Tuesday, 13 August 2013
( Euler | F# )
let xstr:string = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
let chars = xstr.ToCharArray()

let product5startingat x chars =
    let mutable count = 1
    for i in x..x+4 do
        let value = Array.sub chars i 1
        let valueint = int(new string(value))
        count <- count * valueint
    count

let mutable largest = 0
for i in 0..995 do
    let result = product5startingat i chars
    if(result > largest) then
        largest <- result

printfn "%i" largest

An imperative style

let str = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"

// Converts string into a sequence of digits
let digits =
    Seq.map (fun x -> int (System.Char.GetNumericValue x)) str

// Takes every subsequent 5 digits - Seq.windowed.  Multiply them together Seq.reduce applied to each element in the sequence with Seq.map
// then find the maximum with Seq.max
// seq.windowed turns 1000 element list into 996 arrays of subsequences of consecutive digits
let maxproduct num list =
    Seq.max (Seq.map (fun x -> Seq.reduce (*) x) (Seq.windowed num list))

let a = maxproduct 5 digits
printfn "%i" a

Functional from http://blog.asymptotic.co.uk/2009/12/project-euler-in-f-problem-8/

| | # 
# Monday, 12 August 2013
( Euler | F# )
let isPrime x =
    if (x = 2) then
        true
    elif (x%2 = 0) then
        false
    else
        let rec loop i max =
            // This is a prime
            if i >= (max/2) then
            //if i >= int((sqrt(float max))) then
                true
            // Is it divisible by any other other
            elif max%i = 0 then
                false
            else
                loop (i+1) max
        loop 3 x

let getxthPrime numberPrimesToFind =
    let mutable counterOfPrimesFound = 0
    let mutable numberToTry = 2
    while (counterOfPrimesFound < numberPrimesToFind) do
        if (isPrime numberToTry) then
            counterOfPrimesFound <- counterOfPrimesFound + 1
        numberToTry <- numberToTry + 1
    numberToTry-1

printfn "%i" (getxthPrime 10001)

[<Fact>]
let getxthPrime_given6_13() = Assert.Equal(13, getxthPrime 6)


[<Fact>]
let isPrime_given2_true() = Assert.True(isPrime 2)
[<Fact>]
let isPrime_given3_true() = Assert.True(isPrime 3)
[<Fact>]
let isPrime_given4_false() = Assert.False(isPrime 4)
[<Fact>]
let isPrime_given5_true() = Assert.True(isPrime 5)
[<Fact>]
let isPrime_given6_fal() = Assert.False(isPrime 6)
[<Fact>]
let isPrime_given7_true() = Assert.True(isPrime 7)
[<Fact>]
let isPrime_given8_false() = Assert.False(isPrime 8)
[<Fact>]
let isPrime_given9_false() = Assert.False(isPrime 9)
[<Fact>]
let isPrime_given13_true() = Assert.True(isPrime 13)
[<Fact>]
let isPrime_given15_fal() = Assert.False(isPrime 15)

Checks up to maxvalue/2.

let isPrime x =
    if (x = 2) then
        true
    elif (x%2 = 0) then
        false
    else
        let maxI = int(sqrt(float x))+1

        let rec notDivisible i =
            if i > maxI then
                true
            elif x%i = 0 then
                false
            else
                notDivisible (i+2)

        notDivisible 3

Checks up to the squareroot.

let isPrime n = {2L .. n |> float |> sqrt |> int64}
                |> Seq.forall(fun i -> n%i <> 0L)

let primes = seq {1L .. System.Int64.MaxValue}
                |> Seq.filter(isPrime)

let ans = Seq.nth 10001 primes

printfn "%i" ans

Using sequences

Links to other slns: http://breadthfirst.wordpress.com/2010/06/18/project-euler-problem-7/ and http://diditwith.net/2009/01/20/YAPESProblemSevenPart2.aspx

| | # 
# Saturday, 10 August 2013
( Euler | F# )

let sumOfSquares x = [1 .. x] |> Seq.sumBy(fun i -> i*i)

let squared x = x * x

let squareOfSum x = [1 .. x] |> Seq.sum |> squared

let diff = squareOfSum 100 - sumOfSquares 100

printf "diff: %i " diff


[<Fact>]
let sumOfSqaures_given10_385() = Assert.Equal(385, sumOfSquares 10)

[<Fact>]
let squareOfSum_given10_3025() = Assert.Equal(3025, squareOfSum 10)

Sequences are great.. makes it very easy to not have to do loops.

Forward Pipe – a parameter preceding the function name is piped to the function.

let squareOfSum x = [1 .. x] |> Seq.sum |> fun i -> i * i
| | # 
( Euler | F# )

// x is input, max is number to count up to eg 10
let div1To x max =
    let rec loop i =
        if i > max then
            true
        elif x%i <> 0 then
            false
        else
            loop (i+1)
    loop 1

// Smallest number divisible by all numbers from 1 to 20?
let rec loop i =
    if (div1To i 20) then
        printfn "%i" i
    else
        loop (i+1)
loop 1


[<Fact>]
let div1To10_given2520_true() = Assert.True(div1To 2520 10)

[<Fact>]
let div1To10_given2521_false() = Assert.False(div1To 2521 10)

First time used recursive functions in a very ‘for loop’ manner

let a = List.map (fun i -> 2520.0 / i) [1.0 .. 10.0]
printfn "%A" a

And here is a handy function which prints out the results of 2520.0/i a sanity check really.

| | # 
# Friday, 09 August 2013
( Euler | F# )

First shot

let isPalindrome x =
        let xString = x.ToString()
        let a = xString.ToCharArray()

        let len = a.Length
        let halflen = len/2

        let mutable result = true
       
        for i in 1 .. halflen do
            // Left hand side
            let lhsb = Array.sub a (i-1) 1
            let lhss = new string(lhsb)

            // Right hand side
            let rhsb = Array.sub a (len-i) 1
            let rhss = new string(rhsb)

            if (lhss <> rhss) then
                  result <- false
        result

let mutable largest = 0
for i in 100..999 do
    for k in 100..999 do
        let num = i * k
        if (isPalindrome num) then
            if (num > largest) then
                largest <- num
printfn "%i" largest

Charles’s solution in VBScript

'Eulers Challenge Thingy
'Palindromic factoring
'Find the largest palindrome made from the product of two 3-digit numbers
Option Explicit
Dim palintriple
Dim palinreverse
Dim palinsextuple
Dim firstfactor
Dim sndfactor

'Calculate the Six Digit Palindromic Number First
For palintriple = 999 to 100 Step -1
  ' Reverse eg 789 goes to 987
  palinreverse = StrReverse(palintriple)
  ' eg 789*1000=789,000+987= 789,987
  palinsextuple = (palintriple*1000)+palinreverse
  
    'Now Divide by all of the potential factors
    firstfactor = 999
    Do
     sndfactor = palinsextuple/firstfactor
         If sndfactor = 993 Then wscript.echo "missed it!!!!!"
      If CLng(sndfactor) = sndfactor Then
         If sndfactor < 1000 then
          wscript.echo "Highest Palindromic Number = " & palinsextuple
          wscript.echo "First Three digit factor is " & firstfactor
          wscript.echo "Second Three digit factor is " & sndfactor
          wscript.quit 1
         End If
       End If
      firstfactor=firstfactor-1
    Loop Until firstfactor = 100
Next

James’s Solution

let isPalindrome (x:int) =
    let xString=x.ToString()
    let xLen=xString.Length
    let mutable isPal = true
    for i=0 to xString.Length-1 do
        if (xString.[i]<>xString.[xLen-i-1] ) then
            isPal<-false
    
    isPal

let mutable (sumVals : int)=999+999 //start with highest pairs
let mutable (minVals : int)=100+100 //smallest possible pair for the solution
let mutable (y : int)=0
let mutable (maxSolution : int)=0
let mutable (i : int) =0

while (sumVals>minVals) do //loop
    for x = 999 downto (sumVals/2) do
        y<-sumVals-x
        i<-i+1 //get count of iterations to compare with 'Scott Technique'
        if isPalindrome (x*y) then
            if (x*y>maxSolution) then
                maxSolution<-x*y
                minVals<- int (sqrt(float maxSolution))*2
                printfn "new max : %d" maxSolution
                printfn "new smallest sum of pair : %d" minVals
                
    sumVals<-sumVals-1
printfn "Solution2 : %d" maxSolution
printfn "Iterations : %d" i

and factored down:

let isPalindrome (x:int) =  (x/100000 = x%10 && (x/10000)%10 = (x/10)%10 && (x/1000)%10 = (x/100)%10)
let mutable (maxSolution : int)=0
for sumVals=(999+999) downto 200 do for x = 999 downto (sumVals/2) do if (isPalindrome (x*(sumVals-x)) && ((x*(sumVals-x))>maxSolution)) then maxSolution<-x*(sumVals-x)    
printfn "Solution : %d" maxSolution
| | # 
# Thursday, 08 August 2013
( Euler | F# )

The largest prime factor

This proved quite challenging with using bigints in F#

// A number is prime if can only divide by itself and 1.  Can only be odd.
let isPrime x =
    if (x%2L = 0L) then
        false
    else
        let mutable result = true
        for i in 3L..x/2L do
            if (x%i = 0L) then
                result <- false
        result

let lpFactor x =
    let mutable result = int64(1)
    for i in 3L..x/2L do
        if(x%i = 0L) then
            printfn "%i" i
            if (isPrime i) then
                result <- int64(i)
                printfn "primefact %i" i
    result


let a = (lpFactor 600851475143L)

printfn("Hello world")

[<Fact>]
let lpfactor_13195_29() = Assert.Equal(29L, lpFactor 13195L)

//[<Fact>]
//let lpfactor_answer() = Assert.Equal(2L, lpFactor 600851475143L)


[<Fact>]
let isPrime_3_true() = Assert.True(isPrime 3L)

[<Fact>]
let isPrime_4_false() = Assert.False(isPrime 4L)

[<Fact>]
let isPrime_5() = Assert.True(isPrime 5L)

[<Fact>]
let isPrime_7() = Assert.True(isPrime 7L)

[<Fact>]
let isPrime_9() = Assert.False(isPrime 9L)

[<Fact>]
let isPrime_11() = Assert.True(isPrime 11L)

[<Fact>]
let isPrime_13() = Assert.True(isPrime 13L)

[<Fact>]
let isPrime_15() = Assert.False(isPrime 15L)

Refactor1 – Gradbot’s solution using Recursion

let isPrime x =
    // A prime number can't be even
    if (x%2L = 0L) then
        false
    else
        // Check for divisors (other than 1 and itself) up to half the value of the number eg for 15 will check up to 7
        let maxI = x / 2L

        let rec notDivisible i =
            // If we're reached more than the value to check then we are prime
            if i > maxI then
                true
            // Found a divisor so false
            elif x % i = 0L then
                false
            // Add 2 to the 'loop' and call again
            else
                notDivisible (i + 2L)
        
        // Start at 3
        notDivisible 3L

A good first step for getting rid of the mutable state, and using recursion for the ‘loop’

Refactor2 – Sequences

let isPrime x =
    // A prime number can't be even
    if (x%2L = 0L) then
        false
    else
        // Do all elements in the sequence satisfy the predicate?
        Seq.forall (fun i -> x % i <> 0L) { 3L..2L..x/2L }

Very elegant

let isPrime x =
    // A prime number can't be even
    x%2L <> 0L &&
    // Do all elements in the sequence satisfy the predicate?
    Seq.forall (fun i -> x % i <> 0L) { 3L..2L..x/2L }

A single expression where both return a bool.. it does not evaluate the sequence if even.

let isPrime x =
    // Checking even numbers too here
    { 2L..x/2L } |> Seq.forall (fun i -> x % i <> 0L)
    // Same as doing this
    //Seq.forall (fun i -> x % i <> 0L) { 2L..x/2L }

Simplifying but now checking evens

| | # 
# Wednesday, 31 July 2013
( Euler | F# )

First imperative style try at solving the problem.

“Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.”

  1. // Euler 2
  2. open Xunit
  3.  
  4. // Fibonnaci - accepts the number in the sequence, and returns the fibonnacci number
  5. let fib x =
  6.     // oldA is directly left starting on the fib3
  7.     // oldB is 2 to the left starting on fib3
  8.     let mutable currentFib, oldA, oldB = 0, 2, 1
  9.  
  10.     // Special case
  11.     if (x = 1) then
  12.         currentFib <- 1
  13.  
  14.     // Special case
  15.     if (x = 2) then
  16.         currentFib <- 2
  17.  
  18.     // Starting at the third
  19.     for i in 3..x do
  20.         currentFib <- oldA + oldB
  21.         // Setting up for next time around loop
  22.         oldB <- oldA
  23.         oldA <- currentFib
  24.     currentFib
  25.  
  26. // Loops and gets the result
  27. let mutable count = 0
  28. for i in 1 .. 32 do
  29.     let x = fib i
  30.     // Evens
  31.     if x%2 = 0 then
  32.         count <- count + x
  33.  
  34. printfn "%i" count
  35.  
  36. // Test the fib function
  37. [<Fact>]
  38. let fib_given1_shouldReturn1() =
  39.     Assert.Equal(1, fib 1)
  40.  
  41. let fib_given2_shouldReturnx() =
  42.     Assert.Equal(2, fib 2)
  43.  
  44. [<Fact>]
  45. let fib_given3_shouldReturnx() =
  46.     Assert.Equal(3, fib 3)
  47.  
  48. [<Fact>]
  49. let fib_given4_shouldReturnx() =
  50.     Assert.Equal(5, fib 4)
  51.  
  52. [<Fact>]
  53. let fib_given5_shouldReturnx() =
  54.     Assert.Equal(8, fib 5)
  55.  
  56. [<Fact>]
  57. let fib_given6_shouldReturnx() =
  58.     Assert.Equal(13, fib 6)

Used asserts at the begging to make sure the algorithm was working for all cases.  Add in xunit from NuGet, and reference from the top of the file using open Xunit.  Then as a test runner I use Resharper and xunit.control.  However testdriven.net looks look too.

**understand the non tail recursive function here:

http://stackoverflow.com/questions/2845744/generating-fibonacci-series-in-f

| | # 
# Monday, 29 July 2013
( Euler | F# )

Here is James’s solution to Euler 2

// rec means a recursive function
let rec fib x y n =
    // returns n if we've reached the end point
    if y>4000000 then n
   
    else if (y%2=0) then fib y (x+y) (n+y)
    else fib y (x+y) n
  
let z= fib 1 2 0

printfn "%i" z

As I’ve avoided (like the plague) recursive functions in the past, I though this would be a great opportunity to start!

“Functional programming relies on recursive functions heavily since imperative looping structures are frowned upon” – from a blog on tail recursion http://blogs.msdn.com/b/chrsmith/archive/2008/08/07/understanding-tail-recursion.aspx

A recursive function is a function which calls itself. eg a factorial function  6! = 6 * 5 * 4 * 3 * 2 * 1 = 720

// Non recursive factorial function - negative
let fact x =
    let mutable product = 1
    //for i in x.. -1 ..1 do
    for i = x downto 1 do
        product <- product * i
    product

from http://en.wikibooks.org/wiki/F_Sharp_Programming/Recursion

fact(6) =
        = 6 * fact(6 - 1)
        = 6 * 5 * fact(5 - 1)
        = 6 * 5 * 4 * fact(4 - 1)
        = 6 * 5 * 4 * 3 * fact(3 - 1)
        = 6 * 5 * 4 * 3 * 2 * fact(2 - 1)
        = 6 * 5 * 4 * 3 * 2 * 1 * fact(1 - 1)
        = 6 * 5 * 4 * 3 * 2 * 1 * 1
        = 720
let rec fact x =
    if x < 1 then 1
    else x * fact (x - 1)

image
Started at 6, then built up the recursive callstack.  Now if I keep debugging it will come up the hierarchy evaluating? as it goes.

image

// can we see the evaluation as it happens by putting in a mutable? ie half way through coming back up the hierarchy what is the total?

let rec fact x =
  if x > 2 then
    x * (fact (x - 1))
  else
    x

I find this easier to read

Tail Recursion

A tail recursive funcion is a special case of recursion in which the last instruction executed in the method is the recursive call… as a result, rail-recursive functions can recursive indefinately without consuming stack space.

image
Notice the Call Stack only has the most recent call on it – it doesn’t need to remember where it is.

let rec count n =
    // 1 million
    if n = 1000000 then
        printfn "done"
    else
        if n % 1000 = 0 then
            printfn "n: %i" n

        count (n + 1) (* recursive call *)

count 0

To make it non tail recursive, put in a () after the count, which would return a unit after every call, thus ensuring that the stack has to be kept.

image

| | # 
# Friday, 26 July 2013
( Euler | F# )

First problem solved in F#!!!

Euler1 – “If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.Find the sum of all the multiples of 3 or 5 below 1000.”

open Xunit
 
let mul3 x = 
    x % 3 = 0
 
let mul5 x =
    x % 5 = 0
 
let sumOf x =
    let mutable counter = 0
    // loop x times and if is a mul3 or mul5 add to an overall counter
    for i in 1 .. x-1 do
        if mul3 i then
            counter <- counter + i
        else if mul5 i then
            counter <- counter + i
    counter
 
printfn "%d" (sumOf 1000)
 
[<Fact>]
let sumOf_given10_shouldReturn23() = 
    Assert.Equal(23, sumOf 10)
 
[<Fact>]
let sumOf_given16_shouldReturn60() = 
    Assert.Equal(60, sumOf 16)
 
 
[<Fact>]
let multiple3_given3_shouldReturnTrue() = 
    Assert.True(mul3 3)
 
[<Fact>]
let multiple3_given4_shouldReturnFalse() = 
    Assert.False(mul3 4)
 
[<Fact>]
let multiple3_given5_shouldReturnFalse() = 
    Assert.False(mul3 5)
 
[<Fact>]
let multiple3_given6_shouldReturnFalse() = 
    Assert.True(mul3 6)
 
[<Fact>]
let mul5_given3_shouldReturnFalse() = 
    Assert.False(mul5 3)
 
[<Fact>]
let mul5_given5_shouldReturnTrue() = 
    Assert.True(mul5 5)
 
[<Fact>]
let mul5_given15_shouldReturnTrue() = 
    Assert.True(mul5 15)

Issues / Interest I had

  • Getting R# test runner to debug using xunit (Ctrl U L worked to run all tests in solution)
  • Debugger in VS2012 is just like C# for watching locals
  • Is there a more functional way of doing this without mutability

James’s Strategy

I like this idea of having a range, then filtering out.

// James's list of integers from 1 to 999 inclusive, filtered by either x modulus 3 = 0 or x modulus 5 = 0
let eulerList = List.filter (fun x -> (x % 3 * x % 5) = 0 ) [ 1 .. 999 ]  
let eulerSum = eulerList |> List.sum
printfn "Euler Sum: %d" eulerSum


// Daves refactoring pulling out the checking function
let divisibleBy3Or5 x =  x % 3 = 0 || x % 5 = 0
let listOfDivisibleBy3or5 = List.filter(divisibleBy3Or5) [1..999]
printfn "%A" listOfDivisibleBy3or5
// |> forward pipe.  Pipes result of 1 function to another
let eulerSumDave = listOfDivisibleBy3or5 |> List.sum
printfn "%A" eulerSumDave

// Or on 1 line
printfn "Euler Sumx: %d"  ( List.filter (fun x -> (x % 3 = 0 || x % 5 = 0) ) [ 1 .. 999 ]  |> List.sum)

Other Strategies

As I want to learn F# and the functional way (rather than just solving Euler!) I’m going to look at other strategies when I’ve solved the puzzle – I suspect it is going to be interesting.

// or 1 line using Sequence SumBy
let problem1b =
    [1..999] |> Seq.sumBy(fun x -> if (x%3 = 0 || x%5 = 0) then x else 0)
printfn "%i" problem1b
| | # 
# Thursday, 12 July 2012
( Euler )

Trying CodeAnalysis

image

Interesting suggestions.  I quite like using a in the factorial method.

[TestFixture]
public class E53Tests
{
    [Test]
    public void Factorial_Given_Then()
    {
        BigInteger result = E53.Factorial(3);
        Assert.AreEqual(new BigInteger(6), result);
        result = E53.Factorial(4);
        Assert.AreEqual(new BigInteger(24), result);
        result = E53.Factorial(5);
        Assert.AreEqual(new BigInteger(120), result);
    }

    [Test]
    public void MethodUnderTest_scenario_expectedbehaviour()
    {
        BigInteger result = E53.HowManyWaysToGetrFromnDigits(3,5);
        Assert.AreEqual(new BigInteger(10), result);
        result = E53.HowManyWaysToGetrFromnDigits(2, 5);
        Assert.AreEqual(new BigInteger(10), result);
    }

    [Test]
    public void HowManyValuesGreaterThan1m_Given_ReturnCount()
    {
        int result = E53.HowManyValuesGreaterThan1m();
        Assert.AreEqual(4075, result);
    }
}

public class E53
{
    public static int HowManyValuesGreaterThan1m()
    {
        var list = new List<BigInteger>();
        for (int n = 1; n <= 100; n++)
        {
            for (int r = 1; r <= n; r++)
            {
                BigInteger result = HowManyWaysToGetrFromnDigits(r, n);
                if (result > 1000000)
                {
                    list.Add(result);
                }
            }
        }
        return list.Count;
    }

    public static BigInteger HowManyWaysToGetrFromnDigits(int r, int n)
    {
        BigInteger top = Factorial(n);
        BigInteger bracket = Factorial(n - r);
        BigInteger bottom = Factorial(r)*bracket;
        BigInteger result = top/bottom;
        return result;
    }

    public static BigInteger Factorial(int a)
    {
        if (a == 0) return 1;
        BigInteger number = new BigInteger(a);
        for (int i = a-1; i > 1; i--)
        {
            number = number * i;
        }
        return number;
    }
}
  • TDD helped get the answer right the first time
  • Interesting to explore FX Cop (Code Analysis) suggestions.
| | # 
# Wednesday, 11 July 2012
( Euler )
[TestFixture]
public class E52Tests
{
    [Test]
    public void ContainsSameDigits_TestCase_True()
    {
        bool result = E52.ContainsSameDigits(125874,251748);
        Assert.IsTrue(result);
    }

    [Test]
    public void ContainsSameDigits_TestCaseBad_False()
    {
        bool result = E52.ContainsSameDigits(125873, 251748);
        Assert.False(result);
    }

    [Test]
    public void ContainsSameDigits_EdgeBad_False()
    {
        bool result = E52.ContainsSameDigits(111, 11);
        Assert.False(result);
    }

    [Test]
    public void ContainsSameDigits_EdgeBadb_False()
    {
        bool result = E52.ContainsSameDigits(1111, 1112);
        Assert.False(result);
    }

    [Test]
    public void DoubleContainsSameDigits_GivenGood_True()
    {
        bool result = E52.DoesFactor(125874,2);
        Assert.True(result);
    }

    [Test]
    public void FindSmallestInt_Given_Answer()
    {
        int result = E52.FindSmallestInt();
        Assert.AreEqual(142857, result);
    }
}

public class E52
{
    public static int FindSmallestInt()
    {
        for (int i = 10; i < 1000000; i++)
        {
            if (DoesFactor(i, 2))
            {
                if (DoesFactor(i, 3))
                {
                    if (DoesFactor(i, 4))
                    {
                        if (DoesFactor(i, 5))
                        {
                            if (DoesFactor(i, 6))
                            {
                                return i;
                            }
                        }
                    }
                }
            }
        }
        return -1;
    }

    public static bool DoesFactor(int a, int multiple)
    {
        int multiplied = a*multiple;
        if (!ContainsSameDigits(a, multiplied)) return false;
        return true;
    }

    public static bool ContainsSameDigits(int a, int b)
    {
        bool result = true;
        char[] arrayA = a.ToString().ToCharArray();
        char[] arrayB = b.ToString().ToCharArray();

        if (arrayA.Length != arrayB.Length) return false;

        foreach (var character in arrayA)
        {
            if (!arrayB.Contains(character)) return false;
        }
        foreach (var character in arrayB)
        {
            if (!arrayA.Contains(character)) return false;
        }
        return result;
    }
}

using GitHib again https://github.com/djhmateer/Euler52

  • Good to be using TDD and have testable methods
| | # 
( Euler )

A tough one to understand the problem.

“Find the smallest prime which, by changing the same part of that number can form eight different primes”

I went for the simplest solution to start with

[TestFixture]
 public class E51Tests
 {
     //Find the smallest prime which, by changing the same part of that number
     //can form eight different primes
     //x2x3x3: 929393 828383 626363 525353 424343 323333 222323 121313
     [Test]
     public void FindSmallestPrime_Given_Return()
     {
         int result = E51.FindSmallestPrime();
         Assert.AreEqual(121313, result);
     }
 }

 public class E51
 {
     public static int FindSmallestPrime()
     {
         //assume 6 digits will be required
         for (int a = 100003; a <= 999999; a = a + 2)
         {
             if (IsPrime(a))
             {
                 string s = a.ToString();
                 char[] array = s.ToCharArray();
                 //pick a digit to use..but not last digit as this wouldn't allow 8 primes
                 //leading 0's not permitted
                 //looking through for a triplet of numbers in the first 5 digits
                 //that would be exchanged for a total of 8 primes
                 //0 means don't change the digit
                 for (int i = 0; i <= 1; i++)
                 {
                     for (int j = 0; j <= 1; j++)
                     {
                         for (int k = 0; k <= 1; k++)
                         {
                             for (int n = 0; n <= 1; n++)
                             {
                                 for (int p = 0; p <= 1; p++)
                                 {
                                     for (int q = 0; q <= 1; q++)
                                     {
                                         var listPrimesInFamily = new List<int>();

                                         //try changing digits
                                         for (int m = 0; m <= 9; m++)
                                         {
                                             //reset the array
                                             s = a.ToString();
                                             array = s.ToCharArray();

                                             if (i == 1) array[0] = (char)(m + 48);
                                             if (j == 1) array[1] = (char)(m + 48);
                                             if (k == 1) array[2] = (char)(m + 48);
                                             if (n == 1) array[3] = (char)(m + 48);
                                             if (p == 1) array[4] = (char)(m + 48);
                                             if (q == 1) array[5] = (char)(m + 48);

                                             //Console.WriteLine("{0},{1},{2},{3},{4},{5}",i,j,k,n,p,q);
                                             string num = new string(array);
                                             int numChanged = Convert.ToInt32(num);
                                             //Console.WriteLine("c:{0}",num);
                                             if (IsPrime(numChanged))
                                             {
                                                 if (numChanged > 100000)
                                                 {
                                                     if (!listPrimesInFamily.Contains(numChanged))
                                                     {
                                                         listPrimesInFamily.Add(numChanged);
                                                     }
                                                 }
                                             }
                                         }
                                         if (listPrimesInFamily.Count == 8)
                                         {
                                             Console.WriteLine("{1}, {0}", listPrimesInFamily.Count, a);
                                             foreach (var i1 in listPrimesInFamily)
                                             {
                                                 Console.WriteLine("  {0}", i1);
                                             }
                                             return listPrimesInFamily.OrderBy(x => x).FirstOrDefault();
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         return -1;
     }

     public static bool IsPrime(long a)
     {
         if (a == 0) return false;
         if (a == 1) return false;
         if (a == 2) return true;
         for (int i = 2; i <= Math.Sqrt(a); i++)
         {
             if (a % i == 0)
             {
                 return false;
             }
         }
         return true;
     }
 }

 

image

Using Github for windows was very useful as it allowed me to go back to previous versions of code, and to keep my current solution clean.

In retrospect:

  • Difficult problem to grasp what was meant
  • Didn’t use TDD as much and got bogged down with a simple error
  • An interesting one
| | # 
# Sunday, 08 July 2012
( Euler )

http://stackoverflow.com/questions/1890093/converting-a-generic-list-to-a-csv-string

image

Am working outside on the deck

image

Keeping an eye on the temps on my CPUs and GPU.. anything > 80 is cause for concern..and 90’s something wrong.

Also trying out Git For Windows.

[TestFixture]
public class E51Tests
{
    [Test]
    public void GetAll8DigitPrimes_Given_ReturnListPrimes()
    {
        List<int> result = E51.GetAll8DigitPrimes();
        Assert.AreEqual(1, result.Count);
    }

    [Test]
    public void ConvertListIntToCSVString_GivenListInt_ReturnCSVString()
    {
        var list = new List<int>() { 3, 5, 7, 11 };
        var result = E51.ConvertListIntToCSVString(list);
        Assert.AreEqual("3,5,7,11", result);
    }

    [Test]
    public void ReadCSVAndConvertToList_Given_ReturnList()
    {
       List<int> result = E51.ReadCSVAndConvertToList();
       CollectionAssert.IsNotEmpty(result);
    }

    [Test]
    public void SmallestPrimeIn8PrimeFamily_Given_Return()
    {
        var result = E51.SmallestPrimeIn8PrimeFamily();
        Assert.AreEqual(1, result);
    }
}

public class E51
{
    public static int SmallestPrimeIn8PrimeFamily()
    {
        int smallestPrimeSoFar = 99999999;
        List<int> listOfPrimes = E51.ReadCSVAndConvertToList();
        foreach (int p in listOfPrimes)
        {
            string s = p.ToString();
            //pick a digit
            for (int i = 0; i <= 7; i++)
            {
                char digit = s[i];
                //replace 1 or more of the other digits
                for (int j = 0; j <= 7; j++)
                {
                    if (i != j)
                    {
                        string numToTry = s;
                        var sb = new StringBuilder(numToTry);
                        sb[j] = digit;
                        string numChanged = sb.ToString();

                        //see if smallest
                        int num = Convert.ToInt32(numChanged);
                        if (num > 10000000)
                        {
                            if (num < smallestPrimeSoFar)
                            {
                                if (IsPrime(num))
                                {
                                    Console.WriteLine(num);
                                    smallestPrimeSoFar = num;
                                }
                            }
                        }
                    }
                }

            }

            //see if prime
        }
        return smallestPrimeSoFar;
    }

    public static List<int> ReadCSVAndConvertToList()
    {
        var list = new List<int>();
        string csv = File.ReadAllText(@"e:\temp\primes.csv");
        string[] array = csv.Split(',');
        foreach (var s in array)
        {
            list.Add(Convert.ToInt32(s));
        }
        return list;
    }

    public static string ConvertListIntToCSVString(List<int> list)
    {
        string csv = String.Join(",", list.Select(x => x.ToString()).ToArray());
        return csv;
    }

    public static List<int> GetAll8DigitPrimes()
    {
        var list = new List<int>();
        //for (int i = 10000000; i <= 99999999; i++)
        for (int i = 10000001; i <= 11199999; i = i + 2)
        {
            if (IsPrime(i))
            {
                list.Add(i);
                //Console.WriteLine("{0:N0}",i);
            }
        }
        return list;
    }

    public static bool IsPrime(long a)
    {
        if (a == 1) return false;
        if (a == 2) return true;
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}

Code that works but does not solve this problem.  Had to do this to fully understand the problem.

  • Read / Write files
  • Convert both ways List to CSV
| | # 
# Wednesday, 04 July 2012
( Euler )
[TestFixture]
public class E50Tests
{
    [Test]
    public void LongestSumOfConsecutivePrimesBelow_Given100_Return41()
    {
        int result = E50.LongestSumOfConsecutivePrimesBelow(100);
        Assert.AreEqual(41, result);
    }

    [Test]
    public void LongestSumOfConsecutivePrimesBelow_Given1000_Return953()
    {
        int result = E50.LongestSumOfConsecutivePrimesBelow(1000);
        Assert.AreEqual(953, result);
    }

    [Test]
    public void LongestSumOfConsecutivePrimesBelow_Given10000_Return()
    {
        int result = E50.LongestSumOfConsecutivePrimesBelow(1000000);
        Assert.AreEqual(997651, result);
    }
}

public class E50
{
    public static int LongestSumOfConsecutivePrimesBelow(int max)
    {
        var list = new List<int>();
        //a rough number of primes
        for (int i = 2; i <= max/2; i++)
        {
           if (IsPrime(i)) list.Add(i);
        }

        //starting at every place in list
        int largestNumberOfConsecTerms = 1;
        int largestSum = 0;
        for (int i = 0; i < list.Count; i++)
        {
            int sum = list[i];
            int numberConsecTerms = 1;
            //ending at every place in list
            for (int j = i+1; j < list.Count; j++)
            {
                sum += list[j];
                if (sum > max)
                {
                    break;
                }
                numberConsecTerms++;
                if (IsPrime(sum))
                {
                    if (numberConsecTerms >= largestNumberOfConsecTerms)
                    {
                        largestNumberOfConsecTerms = numberConsecTerms;
                        largestSum = sum;
                    }
                }
            }
        }
        return largestSum;
    }
    
    public static bool IsPrime(long a)
    {
        if (a == 1) return false;
        if (a == 2) return true;
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}

Get primes roughly in the right area.  Start at every item of list, and end at every item in list.  See which sums to the most, and how many consecutive numbers.

| | # 
( Euler )
[TestFixture]
public class E49Tests
{
    [Test]
    public void ReturnPermutationsOfFourDigit_GivenInt1234_ReturnAllPermutations()
    {
        List<int> result = E49.ReturnPermutationsOfFourDigit(1234);
        Assert.AreEqual(24, result.Count);
        CollectionAssert.IsSubsetOf(new List<int> { 1234, 4321 }, result);
    }

    [Test]
    public void ReturnPermutationsOfFourDigit_GivenInt_ReturnAllPermutations()
    {
        List<int> result = E49.ReturnPermutationsOfFourDigitHelper(1487);
        Assert.AreEqual(24, result.Count);
        CollectionAssert.IsSubsetOf(new List<int> { 4817, 8147 }, result);
    }

    [Test]
    public void ReturnPermutationsOfFourDigit_GivenInt2969_ReturnAllPermutations()
    {
        List<int> result = E49.ReturnPermutationsOfFourDigitHelper(2969);
        Assert.AreEqual(12, result.Count);
        CollectionAssert.IsSubsetOf(new List<int> { 6299 }, result);
    }

    //[Test]
    public void FindArithmeticSequence_Given_ReturnConcat()
    {
        string result = E49.FindArithmeticSequence(1487);
        Assert.AreEqual("148748178147", result);
    }

    [Test]
    public void FindArithmeticSequence_Given1488_ReturnConcat()
    {
        string result = E49.FindArithmeticSequence(1000);
        Assert.AreEqual("296962999629", result);
    }
}

public class E49
{
    public static List<int> ReturnPermutationsOfFourDigitHelper(int i)
    {
        var retList = new List<int>();
        string incoming = i.ToString();
        List<int> helper = ReturnPermutationsOfFourDigit(1234);
        foreach (int number in helper)
        {
            string s = number.ToString();
            int d0 = Convert.ToInt32(s.Substring(0, 1)) - 1;
            int d1 = Convert.ToInt32(s.Substring(1, 1)) - 1;
            int d2 = Convert.ToInt32(s.Substring(2, 1)) - 1;
            int d3 = Convert.ToInt32(s.Substring(3, 1)) - 1;

            string first = incoming.Substring(d0, 1);
            string second = incoming.Substring(d1, 1);
            string third = incoming.Substring(d2, 1);
            string fourth = incoming.Substring(d3, 1);

            string newNumber = first + second + third + fourth;
            int n = Convert.ToInt32(newNumber);
            retList.Add(n);
        }
        //if 1123 is i.. then inherently we'll have duplicates
        return retList.Distinct().ToList();
    }

    public static List<int> ReturnPermutationsOfFourDigit(int a)
    {
        var list = new List<int>();
        string number = a.ToString();
        string n0 = number.Substring(0, 1);
        string n1 = number.Substring(1, 1);
        string n2 = number.Substring(2, 1);
        string n3 = number.Substring(3, 1);
        var listString = new List<string>() { n0, n1, n2, n3 };
        for (int i = 0; i < 4; i++)
        {
            for (int j = 0; j < 4; j++)
            {
                for (int k = 0; k < 4; k++)
                {
                    for (int l = 0; l < 4; l++)
                    {
                        var h = new HashSet<int>();
                        //don't want duplicates eg 1111
                        string temp = listString[i] + listString[j] + listString[k] + listString[l];
                        bool duplicates = false;
                        foreach (var ch in temp)
                        {
                            if (!h.Add(ch))
                            {
                                duplicates = true;
                            }
                        }
                        if (!duplicates)
                        {
                            int num = Convert.ToInt32(temp);
                            list.Add(num);
                        }
                    }
                }
            }
        }
        return list;
    }

    public static string FindArithmeticSequence(int start)
    {
        for (int i = start; i <= 9999; i++)
        {
            List<int> list = ReturnPermutationsOfFourDigitHelper(i);
            var listOfPrimes = new List<int>();
            foreach (int perm in list)
            {
                if (perm > 1000)
                {
                    if (IsPrime(perm))
                    {
                        listOfPrimes.Add(perm);
                    }
                }
            }

            list.Sort();
            listOfPrimes.Sort();

            if (listOfPrimes.Count >= 3)
            {
                //see if there is a 3330 increase anywhere in sequence
                //don't know where to start.. so try 0.
                for (int j = 0; j < listOfPrimes.Count - 2; j++)
                {
                    int prime2 = listOfPrimes[j] + 3330;
                    if (listOfPrimes.Contains(prime2))
                    {
                        int prime3 = prime2 + 3330;
                        if (listOfPrimes.Contains(prime3))
                        {
                            string result = listOfPrimes[j].ToString() + prime2.ToString() + prime3.ToString();
                            if (result != "148748178147")
                            {
                                return result;
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

    public static bool IsPrime(long a)
    {
        if (a == 1) return false;
        if (a == 2) return true;
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}

Ambiguous question, which turned into some interesting code.  Used HashSet for the first time as a way of checking for duplicates.  Used Linq to only return distinct items.  Came up with own simple way of getting all permutations of a series of numbers, even if that series contains duplicates.  I used a mapping for this.

| | # 
# Tuesday, 03 July 2012
( Euler )
[TestFixture]
public class E48Tests
{
    [Test]
    public void Power_Given2_4()
    {
        BigInteger result = E48.Power(2);
        Assert.AreEqual(new BigInteger(4), result);
    }

    [Test]
    public void Power_Given3_27()
    {
        BigInteger result = E48.Power(3);
        Assert.AreEqual(new BigInteger(27), result);
    }

    [Test]
    public void ReturnSeries_Given10_Return10405071317()
    {
        BigInteger result = E48.ReturnSeries(10);
        Assert.AreEqual(new BigInteger(10405071317), result);
    }

    [Test]
    public void ReturnLast10DigitsOfSeries_Given1000_Return()
    {
        String result = E48.ReturnLast10DigitsOfSeries(1000);
        Assert.AreEqual("9110846700", result);
    }
}

public class E48
{
    public static string ReturnLast10DigitsOfSeries(int i)
    {
        BigInteger result = ReturnSeries(1000);
        string s = result.ToString();
        string s2 = s.Substring(s.Length - 10, 10);
        return s2;
    }

    public static BigInteger ReturnSeries(int a)
    {
        BigInteger number = new BigInteger();
        for (int i = 1; i <= a; i++)
        {
            number += Power(i);
        }
        return number;
    }

    public static BigInteger Power(int a)
    {
        BigInteger number = new BigInteger(a);
        for (int i = 1; i < a; i++)
        {
            number = number*a;
        }
        return number;
    }
}
| | # 
( Euler )
[TestFixture]
public class E47Tests
{
    [Test]
    public void GetPrimeFactors_Given14_Return2and7()
    {
        List<int> result = E47.GetPrimeFactors(14);
        CollectionAssert.AreEqual(new List<int> {2, 7}, result);
    }

    [Test]
    public void GetPrimeFactors_Given15_Return3and5()
    {
        List<int> result = E47.GetPrimeFactors(15);
        CollectionAssert.AreEqual(new List<int> { 3, 5 }, result);
    }

    [Test]
    public void GetPrimeFactors_Given644_Return2and7and23()
    {
        List<int> result = E47.GetPrimeFactors(644);
        CollectionAssert.AreEqual(new List<int> { 2, 7,23 }, result);
    }

    [Test]
    public void GetPrimeFactors_Given645_Return()
    {
        List<int> result = E47.GetPrimeFactors(645);
        CollectionAssert.AreEqual(new List<int> { 3,5,43 }, result);
        result = E47.GetPrimeFactors(646);
        CollectionAssert.AreEqual(new List<int> { 2,17,19 }, result);
    }

    [Test]
    public void FindFirstFourConsecutiveIntegersToHaveDistinctPrimeFactors_Give_ReturnLowestPrimeFactor()
    {
        int result = E47.FindFirstFourConsecutiveIntegersToHaveDistinctPrimeFactors();
        Assert.AreEqual(134043, result);
    }
}

public class E47
{
    public static int FindFirstFourConsecutiveIntegersToHaveDistinctPrimeFactors()
    {
        var consecIntegers = new List<int>();
        for (int i = 10; i < 10000000; i++)
        {
            List<int> result = GetPrimeFactors(i);
            if (result.Count == 4)
            {
                Console.WriteLine("{0}, count: {1}",i, consecIntegers.Count);
                if (consecIntegers.Contains(i - 1))
                {
                    consecIntegers.Add(i);
                    if (consecIntegers.Count == 4)
                    {
                        return consecIntegers[0];
                    }
                }
                else
                {
                    //creating a new list, or using Clear
                    //consecIntegers = new List<int>();
                    consecIntegers.Clear();
                    consecIntegers.Add(i);
                }
            }
        }
        return 0;
    }

    public static List<int> GetPrimeFactors(int a)
    {
        var primeFactors = new List<int>();
        for (int i = 2; i <= a/2; i++)
        {
            if (a%i == 0)
            {
                if (IsPrime(i))
                {
                    primeFactors.Add(i);
                }
            }
        }
        return primeFactors;
    }

    public static bool IsPrime(long a)
    {
        if (a == 1) return false;
        if (a == 2) return true;
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a%i == 0)
            {
                return false;
            }
        }
        return true;
    }
}
| | # 
# Sunday, 01 July 2012
( Euler )
[TestFixture]
public class E46Tests
{
    [Test]
    public void MethodUnderTest_scenario_expectedbehaviour()
    {
        var result = E46.MakeListOfPrimes(100);
        CollectionAssert.IsSubsetOf(new List<long> {2,3,5,7,11}, result);   
    }

    [Test]
    public void IsConjecture_Given9_ReturnTrue()
    {
        List<long> list = E46.MakeListOfPrimes(100);

        bool result = E46.IsConjecture(9,list);
        Assert.IsTrue(result);
        result = E46.IsConjecture(11,list); //not in list on website but good
        Assert.IsTrue(result);
        result = E46.IsConjecture(15,list);
        Assert.IsTrue(result);
        result = E46.IsConjecture(21,list);
        Assert.IsTrue(result);
        result = E46.IsConjecture(33,list);
        Assert.IsTrue(result);
    }
    
    [Test]
    public void IsConjecture_GivenBad_ReturnFalse()
    {
        var list = E46.MakeListOfPrimes(100);

        bool result = E46.IsConjecture(8,list);
        Assert.IsFalse(result);
        result = E46.IsConjecture(10,list);
        Assert.IsFalse(result);
        result = E46.IsConjecture(22,list);
        Assert.IsFalse(result);
    }

    [Test]
    public void SolveSmallestOddComposite_Given_ReturnComposite()
    {
        long result = E46.SolveSmallestOddComposite();
        Assert.AreEqual(5777, result);
    }
}

public class E46
{
    public static long SolveSmallestOddComposite()
    {
        List<long> list = MakeListOfPrimes(10000);
        for (long i = 3; i < 1000000; i=i+2)
        {
            //if an odd composite number
            if (!IsPrime(i))
            {
                //if cannot be written as the sum of a prime and twice a square
                if (!IsConjecture(i, list))
                {
                    return i;
                }
            }
        }
        return 0;
    }

    public static bool IsConjecture(long number, List<long> list)
    {
        if (number % 2 == 0) return false;

        foreach (var prime in list)
        {
            //try all primes less than number - 2
            if (prime > number -2) return false;

            //try all whole numbers up to number-prime..then square root
            long maxPossibleNumberToAdd = (long)Math.Sqrt(number - prime);
            for (int i = 1; i <= maxPossibleNumberToAdd; i++)
            {
                if ((prime + 2 * (i * i)) == number) return true;
            }
        }
        return false;
    }

    public static List<long> MakeListOfPrimes(long max)
    {
        var list = new List<long>();
        list.Add(2);
        for (int i = 3; i <= max; i=i+2)
        {
            if (IsPrime(i))
            {
                list.Add(i);
            }
        }
        return list;
    }

    public static bool IsPrime(long a)
    {
        if (a == 1) return false;
        if (a == 2) return true;
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}
| | # 
# Saturday, 30 June 2012
( Euler )

How to get the inverse of this function:

x = n(3n-1)/2

http://math.stackexchange.com/questions/164645/steps-to-get-inverse-of-pentagonal

How to create equations in Math.Stackexchange using TeX

http://meta.math.stackexchange.com/questions/107/faq-for-math-stackexchange

So then I tried to get the inverse of Triangle and Hexagonal:

    [TestFixture]
    public class E45Tests
    {
        [Test]
        public void IsTriangle_GivenTriangleNumber_ReturnN()
        {
            int result = E45.IsTriangle(40755);
            Assert.AreEqual(285, result);
        }
        
        [Test]
        public void IsTriangle_GivenTriangleNumber6_ReturnN()
        {
            int result = E45.IsTriangle(6);
            Assert.AreEqual(3, result);
            result = E45.IsTriangle(15);
            Assert.AreEqual(5, result);
        }

        [Test]
        public void IsTriangle_GivenBadTriangle_Return0()
        {
            int result = E45.IsTriangle(9);
            Assert.AreEqual(0, result);
        }

        [Test]
        public void IsPentagonal_GivenPentNumber12_ReturnN()
        {
            int result = E45.IsPentagonal(12);
            Assert.AreEqual(3, result);
        }
        
        [Test]
        public void IsPentagonal_GivenPentNumber35_ReturnN()
        {
            int result = E45.IsPentagonal(35);
            Assert.AreEqual(5, result);
        }

        [Test]
        public void IsPentagonal_GivenPentNumber_ReturnN()
        {
            int result = E45.IsPentagonal(40755);
            Assert.AreEqual(165, result);
        }

        [Test]
        public void IsPentagonal_GivenBadPentNumber_Return0()
        {
            int result = E45.IsPentagonal(40756);
            Assert.AreEqual(0, result);
        }

        [Test]
        public void IsHexagonal_GivenHexNumber15_ReturnN()
        {
            int result = E45.IsHexagonal(15);
            Assert.AreEqual(3, result);
        }

        [Test]
        public void IsHexagonal_GivenHexNumber_ReturnN()
        {
            int result = E45.IsHexagonal(40755);
            Assert.AreEqual(143, result);
        }

        [Test]
        public void IsHexagonal_GivenHexNumberBad_Return0()
        {
            int result = E45.IsHexagonal(22);
            Assert.AreEqual(0, result);
        }

        [Test]
        public void Solve_Given_Return()
        {
            long result = E45.Solve();
            Assert.AreEqual(1, result);
            //1533776805

        }

    }

    public class E45
    {
        public static long Solve()
        {
            for (long i = 40756; i < 9951140855; i++)
            {
                if (IsTriangle(i) != 0)
                {
                    if (IsHexagonal(i) != 0)
                    {
                        if (IsPentagonal(i) != 0)
                        {
                            return i;
                        }
                    }
                }
            }
            return 0;
        }

        public static int IsTriangle(long i)
        {
            double t = (Math.Sqrt(1 + 8 * i) - 1.0) / 2.0;
            if (t == (int)t)
            {
                return (int)t;
            }
            return 0;
        }

        public static int IsPentagonal(long i)
        {
            double t = (Math.Sqrt(1 + 24 * i) + 1.0) / 6.0;
            if (t == (int)t)
            {
                return (int)t;
            }
            return 0;
        }

        public static int IsHexagonal(long i)
        {
            double t = (Math.Sqrt(1 + 8 * i) + 1.0) / 4.0;
            if (t == (int)t)
            {
                return (int)t;
            }
            return 0;
        }
    }
}

Hardest part was working out the inverse of the quadratics.

http://www.wikihow.com/Find-the-Inverse-of-a-Quadratic-Function

| | # 
# Thursday, 28 June 2012
( Euler )

http://www.quickmath.com/webMathematica3/quickmath/equations/solve/basic.jsp#c=solve_basicsolveequation&v1=x%3Dn(3n-1)%2F2&v2=n

Inverse function was the trick here – getting IsPentagonal to work

[TestFixture]
public class E44Tests
{
    [Test]
    public void ReturnPentagonal_Given1x10_ReturnListOfPents()
    {
        List<long> result = E44.ReturnPentagonalList(1, 10);
        Assert.AreEqual(10, result.Count);
        CollectionAssert.AreEquivalent(result, new List<int> { 1, 5, 12, 22, 35, 51, 70, 92, 117, 145 });
    }

    [Test]
    public void IsPentagonal_Given51_True()
    {
        bool result = E44.IsPentagonal(51);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPentagonal_Given29_False()
    {
        bool result = E44.IsPentagonal(29);
        Assert.IsFalse(result);
    }

    [Test]
    public void IsPentagonal_Given48_False()
    {
        bool result = E44.IsPentagonal(48);
        Assert.IsFalse(result);
    }

    [Test]
    public void IsPentagonal_Given125_False()
    {
        bool result = E44.IsPentagonal(125);
        Assert.IsFalse(result);
    }


    [Test]
    public void IsPentagonal_GivenAllNumbersAndCompareToCorrectList_ShouldBeSameAsList()
    {
        var listOfPents = new List<long>();

        listOfPents = E44.ReturnPentagonalList(1, 30000);
        for (int i = 1; i < 100; i++)
        {
            if (E44.IsPentagonal(i))
            {
                CollectionAssert.Contains(listOfPents, i);
            }
        }
    }

    [Test]
    public void FindPairOfPWhereSumAndDiffIsPent_Given_ReturnListPairs()
    {
        List<string> result = E44.FindPairOfPWhereSumAndDiffIsPent();
        Assert.AreEqual(1, result.Count);
        //iPent 1560090, jPent 7042750, sum 8602840, difference 5482660

    }
}

public class E44
{
    public static List<string> FindPairOfPWhereSumAndDiffIsPent()
    {
        var list = new List<string>();
        for (int i = 1; i < 10000; i++)
        {
            Console.WriteLine(i);
            for (int j = 1; j < 10000; j++)
            {
                if (i < j)
                {
                    //sum
                    long iPent = ReturnPentagonal(i);
                    long jPent = ReturnPentagonal(j);
                    long sum = iPent + jPent;
                    if (IsPentagonal(sum))
                    {
                        long difference = jPent - iPent;
                        if (IsPentagonal(difference))
                        {
                            long d = jPent - iPent;
                            string x = iPent + "," + jPent + "," + d;
                            list.Add(x);
                            Console.WriteLine("i: {4}, j: {5}, iPent {0}, jPent {1}, sum {2}, difference {3}", iPent, jPent, sum, difference,i,j);
                        }
                    }
                }
            }
        }
        return list;
    }

    public static bool IsPentagonal(long i)
    {
        double t = (Math.Sqrt(1+ 24 * i) + 1.0) / 6.0;
        if (t == (int)t)
        {
            return true;
        }
        return false;
    }

    public static long ReturnPentagonal(int a)
    {
        long result = a * ((3 * a) - 1) / 2;
        return result;
    }

    public static List<long> ReturnPentagonalList(int a, int b)
    {
        var list = new List<long>();
        for (int i = a; i <= b; i++)
        {
            long result = ReturnPentagonal(i);
            list.Add(result);
        }
        return list;
    }
}
| | # 
( Euler )

image

Using Parallel.For for the first time. 

Goal is to get a sequence of Pandigitals to work with 0x9. ie from:  1023456789 to 9876543210

This is a brute force approach to get the PD’s into a list, which I’ll save to a CSV.

http://stackoverflow.com/questions/2774170/parallel-for-update-variable-outside-of-loop  - race conditions and parallel…caution.

http://stackoverflow.com/questions/10846550/disappointing-performance-with-parallel-for – using each thread/core to do subtotals pattern in parallel.

Delegates / Lambdas / Actions

http://stackoverflow.com/questions/11233704/writing-a-delegate-as-a-func

//delegate
Parallel.For(1023456789, 9876543210, delegate(long i)
                                         {
                                             if (i % 10000000 == 0) Console.WriteLine("{0:N0}", i);
                                             if (IsPanDigital(i))
                                             {
                                                 Console.WriteLine("****" + i);
                                                 list.Add(i); //not thread safe
                                             }
                                         }
    );

//lambda expression
//Parallel.For(1023456789, 1033456789, i =>
//                                         {
//                                             if (i%10000000 == 0) Console.WriteLine("{0:N0}", i);
//                                             if (IsPanDigital(i))
//                                             {
//                                                 list.Add(i);
//                                             }
//                                         }
//    );

I like the delegate syntax.

public static Action<long> Blah(List<long> list)
{
    //return i =>
    //           {
    //               if (i%10000000 == 0) Console.WriteLine("{0:N0}", i);
    //               if (IsPanDigital(i))
    //               {
    //                   list.Add(i);
    //               }
    //           };
    return delegate(long i)
    {
        if (i % 10000000 == 0) Console.WriteLine("{0:N0}", i);
        if (IsPanDigital(i))
        {
            list.Add(i);
        }
    };
}

Can call out to another method Action<long>

Parallel.For(1023456789, 1033456789, Blah(list));

Write Out Sequence

The above brute force is taking about 2 hours.. so new strategy is to write out the sequence smallest to largest:

1023456789
1023456798
1023456879
1023456897

hmm seems hard

Other IsPanDigital Algorithms

google searched and a good one on SO: http://stackoverflow.com/questions/2484892/fastest-algorithm-to-check-if-a-number-is-pandigital

but this didn’t seem to work easily for a long.

Other Part of Problem to reduce size of Pandigital Checking

Reduced size by looking at final 3 digits and only taking the ones which are multiples of 17.  Then same for middle digits multiples of 7.

image

34secs runtime over 8 cores using Parallel.For loop.

[TestFixture]
public class E43Tests
{
    [Test]
    public void SubstringDivOkay_Given1406357289_ReturnTrue()
    {
        bool result = E43.SubstringDivOkay(1406357289);
        Assert.IsTrue(result);
    }

    [Test]
    public void MethodUnderTest_scenario_expectedbehaviour()
    {
        bool result = E43.SubstringDivOkay(3248456789);
        Assert.IsFalse(result);
    }

    [Test]
    public void IsPanDigital_Given1234567890_ReturnTrue()
    {
        bool result = E43.IsPanDigital(1234567890);
        Assert.IsTrue(result);
        result = E43.IsPanDigital(1406357289);
        Assert.IsTrue(result);
    }

    [Test]
    public void GetLast3DigitsDiv17_Given_ReturnList()
    {
        List<string> result = E43.GetLast3DigitsDiv17();
        Assert.AreEqual(58, result.Count);
    }

    [Test]
    public void GetMiddleDigitsDiv7_Given_ReturnList()
    {
        List<string> result = E43.GetMid3DigitsDiv7();
        Assert.AreEqual(143, result.Count);
    }

    [Test]
    public void GetAll0x9PandigitalNumbersSubStringGood_GivenListLast3Digits_ReturnAnswer()
    {
        long result = E43.GetAnswer();
        Assert.AreEqual(16695334890, result);
    }
    //answer 16695334890..in 1hr 43. with strings below
    //making for loop smaller.. 36secs
}

public class E43
{
    public static long GetAnswer()
    {
        var lastDigits = E43.GetLast3DigitsDiv17();
        var midDigits = E43.GetMid3DigitsDiv7();
        long result = E43.GetAll0x9PandigitalNumbersSubStringGood(lastDigits, midDigits);
        return result;
    }

    public static List<string> GetMid3DigitsDiv7()
    {
        var list = new List<string>();
        for (int i = 1; i < 1000; i++)
        {
            if (i % 7 == 0)
            {
                if (i < 10)
                {
                    list.Add("00" + i.ToString());
                }
                else if (i < 100)
                {
                    list.Add("0" + i.ToString());
                }
                else
                {
                    list.Add(i.ToString());
                }
            }
        }
        return list;
    }

    public static List<string> GetLast3DigitsDiv17()
    {
        var list = new List<string>();
        for (int i = 1; i < 1000; i++)
        {
            if (i % 17 == 0)
            {
                if (i < 100)
                {
                    list.Add("0" + i.ToString());
                }
                else
                {
                    list.Add(i.ToString());
                }
            }
        }
        return list;
    }

    public static bool SubstringDivOkay(long i)
    {
        string s = i.ToString();
        string d2 = s.Substring(1, 1);
        string d3 = s.Substring(2, 1);
        string d4 = s.Substring(3, 1);
        string d5 = s.Substring(4, 1);
        string d6 = s.Substring(5, 1);
        string d7 = s.Substring(6, 1);
        string d8 = s.Substring(7, 1);
        string d9 = s.Substring(8, 1);
        string d10 = s.Substring(9, 1);

        int number2 = Convert.ToInt32(d2 + d3 + d4);
        int number3 = Convert.ToInt32(d3 + d4 + d5);
        int number5 = Convert.ToInt32(d4 + d5 + d6);
        //int number7 = Convert.ToInt32(d5 + d6 + d7);
        int number11 = Convert.ToInt32(d6 + d7 + d8);
        int number13 = Convert.ToInt32(d7 + d8 + d9);
        //int number17 = Convert.ToInt32(d8 + d9 + d10);
        //if (number17 % 17 == 0)
        //{
        if (number13 % 13 == 0)
        {
            if (number11 % 11 == 0)
            {
                //if (number7 % 7 == 0)
                //{
                if (number5 % 5 == 0)
                {
                    if (number3 % 3 == 0)
                    {
                        if (number2 % 2 == 0)
                        {
                            return true;
                        }
                    }
                }
                //}
            }
        }
        //}
        return false;
    }

    public static long GetAll0x9PandigitalNumbersSubStringGood(List<string> lastDigits, List<string> midDigits)
    {
        var listOfPDs = new List<long>();

        Parallel.For(1023, 9923, delegate(long i)
                                     {
                                         if (i%1000 == 0) Console.WriteLine("{0:N0}", i);
                                         //concat mid
                                         foreach (var midDigit in midDigits)
                                         {
                                             //concat last digits
                                             foreach (string lastDigit in lastDigits)
                                             {
                                                 long j = Convert.ToInt64(i.ToString() + midDigit + lastDigit);

                                                 if (SubstringDivOkay(j))
                                                 {
                                                     if (IsPanDigital(j))
                                                     {
                                                         Console.WriteLine("****" + j);
                                                         listOfPDs.Add(j);//not thread safe
                                                     }
                                                 }
                                             }
                                         }
                                     });
     

        long sum = 0;
        foreach (long l in listOfPDs)
        {
            sum += l;
        }
        return sum;
    }

    public static bool IsPanDigital(long number)
    {
        var list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        string s = number.ToString();
        for (int i = 0; i < 10; i++)
        {
            int num = Convert.ToInt32(s.Substring(i, 1));
            if (list.Contains(num))
            {
                list.Remove(num);
            }
            else
            {
                return false;
            }
        }
        return true;
    }
}
| | # 
# Wednesday, 27 June 2012
( Euler )
[TestFixture]
public class E41Tests
{
    [Test]
    public void IsPD_Given2143_ReturnTrue()
    {
        bool result = E41.IsPD(2143);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPD_Given21435_ReturnTrue()
    {
        bool result = E41.IsPD(21435);
        Assert.IsTrue(result);
        result = E41.IsPD(214356798);
        Assert.IsTrue(result);
        result = E41.IsPD(214);
        Assert.IsFalse(result);

    }

    [Test]
    public void IsPDAndPrime_Give2143_ReturnTrue()
    {
        bool result = E41.IsPDAndPrime(2143);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPDAndPrime_Give_Return()
    {
        bool result = E41.IsPDAndPrime(123456789);
        Assert.IsFalse(result);
    }

    [Test]
    public void LargestNDigitPDPrime_Give_Return()
    {
        int result = E41.LargestNDigitPDPrime();
        Assert.AreEqual(1, result);

    }
}

public class E41
{
    public static int LargestNDigitPDPrime()
    {
        int largestSoFar = 0;
        for (int i = 2; i <= 123456789; i++)
        {
            if (i % 1000000 == 0)
            {
                //Console.WriteLine("i is: {0}", i);
            }
            if (IsPDAndPrime(i))
            {
                Console.WriteLine("{0}",i);
                largestSoFar = i;
            }
        }
        return largestSoFar;
    }

    public static bool IsPDAndPrime(int a)
    {
        if (!IsPD(a))
        {
            return false;
        }
        if (!IsPrime(a))
        {
            return false;
        }
        return true;
    }

    public static bool IsPD(int number)
    {
        var list = new List<int>();
        string s = number.ToString();
        for (int i = 1; i <= s.Length; i++)
        {
            list.Add(i);
        }

        for (int i = 0; i < s.Length; i++)
        {
            int num = Convert.ToInt32(s.Substring(i,1));
            if (list.Contains(num))
            {
                list.Remove(num);
            }
            else
            {
                return false;
            }
        }
        return true;
    }

    public static bool IsPrime(int a)
    {
        if (a == 1)
        {
            return false;
        }
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}

TDD’ing.. getting the answer more or less the first time!  Would have been better to step through the PD’s and see if they were prime.

| | # 
( Euler )
[TestFixture]
public class E40Tests
{
    [Test]
    public void ConcatenatePositiveIntegers_Given31AsLengthOfDecimal_ReturnDecimal()
    {
        string result = E40.ConcatenatePositiveIntegers(31);
        Assert.AreEqual("0.123456789101112131415161718192021", result);
    }

    [Test]
    public void GetNthDigit_Given2_Return2()
    {
        int result = E40.GetNthDigit(2);
        Assert.AreEqual(2, result);
    }

    [Test]
    public void GetNthDigit_Given12_Return1()
    {
        int result = E40.GetNthDigit(12);
        Assert.AreEqual(1, result);
        result = E40.GetNthDigit(15);
        Assert.AreEqual(2, result);
    }

    [Test]
    public void FindValueOfExpression_Given_ReturnAnswer()
    {
        int result = E40.FindValueOfExpression();
        Assert.AreEqual(210, result);
    }
}

public class E40
{
    public static int FindValueOfExpression()
    {
        int d1 = GetNthDigit(1);
        int d2 = GetNthDigit(10);
        int d3 = GetNthDigit(100);
        int d4 = GetNthDigit(1000);
        int d5 = GetNthDigit(10000);
        int d6 = GetNthDigit(100000);
        int d7 = GetNthDigit(1000000);

        int result = d1*d2*d3*d4*d5*d6*d7;
        return result;
    }

    public static int GetNthDigit(int n)
    {
        string fullFraction = ConcatenatePositiveIntegers(n);
        fullFraction = fullFraction.Substring(2);
        string numberAsString = fullFraction.Substring(n - 1, 1);
        int number = Convert.ToInt32(numberAsString);
        return number;
    }

    public static string ConcatenatePositiveIntegers(int lengthOfDecimal)
    {
        string result = "0.";
        int i = 1;
        while (result.Length < lengthOfDecimal + 3)
        {
            result += i;
            i++;
        }
        return result;
    }
}
| | # 
# Tuesday, 26 June 2012
( Euler )
[TestFixture]
public class E39Tests
{
    [Test]
    public void RAT_Given120_Return3()
    {
        int result = E39.NumberOfSolutionsGivenPerimeterOfRightAngledTriangle(120);
        Assert.AreEqual(3, result);
    }

    [Test]
    public void GetMaxSolutions_GivenNothing_ReturnValueOfP()
    {
        int result = E39.GetMaxSolutions();
        Assert.AreEqual(840, result);
    }
}

public class E39
{
    public static int GetMaxSolutions()
    {
        int maxSolutions = 0;
        int valueThatGaveMaxSolutions = 0;
        for (int i = 1; i <= 1000; i++)
        {
            int result = NumberOfSolutionsGivenPerimeterOfRightAngledTriangle(i);
            if (result > maxSolutions)
            {
                maxSolutions = result;
                valueThatGaveMaxSolutions = i;
            }
        }
        return valueThatGaveMaxSolutions;
    }

    public static int NumberOfSolutionsGivenPerimeterOfRightAngledTriangle(int p)
    {
        var sidesI = new List<int>();
        int solutions = 0;
        int roughMaxValueOfSide = p/2;
        //its a right angled triangle a^2 +  b^2 = c^2
        for (int i = 1; i < roughMaxValueOfSide; i++)
        {
            for (int j = 1; j < roughMaxValueOfSide; j++)
            {
                for (int k = 1; k < roughMaxValueOfSide; k++)
                {
                    if ((i + j + k) == p)
                    {
                        if (Math.Pow(i, 2) + Math.Pow(j, 2) == Math.Pow(k, 2))
                        {
                            //looking for inverse so don't double up
                            if (!sidesI.Contains(j))
                            {
                                solutions++;
                                //Console.WriteLine("{0}, {1}, {2}", i, j, k);
                                sidesI.Add(i);
                            }
                        }
                    }
                }
            }
        }
        return solutions;
    }
}
| | # 
( Euler )
[TestFixture]
public class E22Tests
{
    [Test]
    public void GetCP_Given192And3_ReturnCP()
    {
        int result = E38.GetConcatenatedProduct(192, 3);
        Assert.AreEqual(192384576, result);
    }

    [Test]
    public void GetCP_Given9And5_ReturnCP()
    {
        int result = E38.GetConcatenatedProduct(9, 5);
        Assert.AreEqual(918273645, result);
    }

    [Test]
    public void IsPanDigital_Given192384576_ReturnTrue()
    {
        bool result = E38.IsPanDigital(192384576);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPanDigital_Given192384577_ReturnFalse()
    {
        bool result = E38.IsPanDigital(192384577);
        Assert.IsFalse(result);
    }

    [Test]
    public void GetLargestPD9DigitNumberWithSeries_Given_ReturnAnswer()
    {
        int result = E38.GetLargestPD9DigitNumberWithSeries();
        Assert.AreEqual(932718654, result);
    }
}

public class E38
{
    public static int GetLargestPD9DigitNumberWithSeries()
    {
        int largestSoFar = 0;
        for (int i = 1; i < 500000; i++)
        {
            for (int j = 1; j < 10; j++)
            {
                int result = GetConcatenatedProduct(i, j);
                if (IsPanDigital(result))
                {
                    if (result > largestSoFar)
                    {
                        largestSoFar = result;
                    }
                }
            }
        }
        return largestSoFar;
    }

    public static bool IsPanDigital(int number)
    {
        string s = number.ToString();
        if (s.Length != 9)
        {
            return false;
        }

        for (int i = 1; i < 10; i++)
        {
            if (!s.Contains(i.ToString()))
            {
                return false;
            }
        }
        return true;
    }

    public static int GetConcatenatedProduct(int number, int max)
    {
        string concat = "";
        for (int i = 1; i <= max; i++)
        {
            int result = number * i;
            concat += result;
        }
        //as we are only intereted in 9
        if (concat.Length > 9)
        {
            return 0;
        }

        return Convert.ToInt32(concat);
    }
}
| | # 
( Euler )
[TestFixture]
public class E37Tests
{
    [Test]
    public void IsTruncatablePrime_Given3797_ReturnTrue()
    {
        bool result = E37.IsTruncatablePrime(3797);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsTruncatablePrime_Given3798_ReturnFalse()
    {
        bool result = E37.IsTruncatablePrime(3798);
        Assert.IsFalse(result);
    }

    [Test]
    public void IsTruncatablePrime_Given13_ReturnFalse()
    {
        bool result = E37.IsTruncatablePrime(13);
        Assert.IsFalse(result);
    }

    //[Test]
    public void PrimesThatAreTruncatable_GivenNothin_ReturnList()
    {
        List<int> result = E37.PrimesThatAreTrucatable();
        Assert.AreEqual(11, result.Count);
    }

    [Test]
    public void FindSumOfPrimes_GivenNothing_ReturnAnswer()
    {
        int result = E37.FindSumOfPrimes();
        Assert.AreEqual(748317, result);
    }
}

public class E37
{
    public static int FindSumOfPrimes()
    {
        List<int> list = E37.PrimesThatAreTrucatable();
        int result = 0;
        foreach (var i in list)
        {
            result += i;
        }
        return result;
    }

    public static List<int> PrimesThatAreTrucatable()
    {
        var truncatable = new List<int>();
        for (int i = 9; i < 1000000; i++)
        {
            if (IsTruncatablePrime(i))
            {
                truncatable.Add(i);
                Console.WriteLine("{0:N0}",i);
            }
        }
        return truncatable;
    }

    public static bool IsTruncatablePrime(int number)
    {
        if (!IsPrime(number))
        {
            return false;
        }

        //taking digits off left
        string s = number.ToString();
        int sLength = s.Length;
        for (int i = 1; i < sLength; i++)
        {
            s = s.Substring(1);
            if (!IsPrime(Convert.ToInt32(s)))
            {
                return false;
            }
        }

        //taking digits off right
        s = number.ToString();
        for (int i = 1; i < sLength; i++)
        {
            s = s.Substring(0,s.Length-1);
            if (!IsPrime(Convert.ToInt32(s)))
            {
                return false;
            }
        }
        return true;
    }

    public static bool IsPrime(int a)
    {
        if (a == 1)
        {
            return false;
        }
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}
| | # 
( Euler )
[TestFixture]
public class E36Tests
{
    [Test]
    public void IsPalindrome_GivenSingleDigits_ReturnTrue()
    {
        bool result = E36.IsPalindrome("1");
        Assert.IsTrue(result);
        result = E36.IsPalindrome("2");
        Assert.IsTrue(result);
        result = E36.IsPalindrome("3");
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPalindrome_Given585_ReturnTrue()
    {
        bool result = E36.IsPalindrome("585");
        Assert.IsTrue(result);
    }
    
    [Test]
    public void IsPalindrome_GivenBinary_ReturnTrue()
    {
        bool result = E36.IsPalindrome("1001001001");
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPalindrome_GivenNonP_ReturnFalse()
    {
        bool result = E36.IsPalindrome("5855");
        Assert.IsFalse(result);
    }

    [Test]
    public void SumAllNumbersPalindromeBase10And2_Given1m_ReturnAnswer()
    {
        int result = E36.SumAllnumbersPalindromeBase10And2(1000000);
        Assert.AreEqual(872187, result);
    }
}

public class E36
{
    public static int SumAllnumbersPalindromeBase10And2(int maxNumber)
    {
        int total = 0;
        //palindrome does not have to have more than 1 digit!
        for (int i = 1; i < maxNumber; i++)
        {
            if (!IsPalindrome(i.ToString()))
            {
                continue;
            }
            //binary
            if (!IsPalindrome(Convert.ToString(i,2)))
            {
                continue;
            }
            Console.WriteLine("{0:N0}",i);
            total += i;
        }
        return total;
    }

    public static bool IsPalindrome(string s)
    {
        string newS = "";
        //reverse the characters and should be the same
        for (int i = s.Length-1; i >= 0; i--)
        {
            newS += s[i];
        }
        if (s == newS)
        {
            return true;
        }
        return false;
    }
}
| | # 
( Euler )
[TestFixture]
public class E35Tests
{
    [Test]
    public void IsPrime_Given2_ReturnTrue()
    {
        bool result = E35.IsPrime(2);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPrime_GivenGoodPrimes_ReturnTrue()
    {
        bool result = E35.IsPrime(7);
        Assert.IsTrue(result);
        result = E35.IsPrime(11);
        Assert.IsTrue(result);
        result = E35.IsPrime(13);
        Assert.IsTrue(result);
        result = E35.IsPrime(17);
        Assert.IsTrue(result);
        result = E35.IsPrime(19);
        Assert.IsTrue(result);
        result = E35.IsPrime(23);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsPrime_GivenBadPrimes_ReturnFalse()
    {
        bool result = E35.IsPrime(4);
        Assert.IsFalse(result);
        result = E35.IsPrime(6);
        Assert.IsFalse(result);
        result = E35.IsPrime(9);
        Assert.IsFalse(result);
        result = E35.IsPrime(10);
        Assert.IsFalse(result);
        result = E35.IsPrime(12);
        Assert.IsFalse(result);
        result = E35.IsPrime(12312312);
        Assert.IsFalse(result);
    }

    [Test]
    public void IsCircularPrime_Given197_ReturnTrue()
    {
        bool result = E35.IsCircularPrime(197);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsCircularPrime_Given19_ReturnFalse()
    {
        bool result = E35.IsCircularPrime(19);
        Assert.IsFalse(result);
    }

    [Test]
    public void GetCircularPrimes_Given100_Return13()
    {
        int result = E35.GetCircularPrimes(100);
        Assert.AreEqual(13, result);
    }

    [Test]
    public void GetCircularPrimes_Given1m_ReturnAnswer()
    {
        int result = E35.GetCircularPrimes(1000000);
        Assert.AreEqual(55, result);
    }
}

public class E35
{
    public static int GetCircularPrimes(int maxNumber)
    {
        int counter = 0;
        for (int i = 2; i < maxNumber; i++)
        {
            if (IsCircularPrime(i))
            {
                counter++;
                Console.WriteLine("{0:N0}", i);
            }
        }
        return counter;
    }

    public static bool IsCircularPrime(int a)
    {
        //change digit order
        //eg put 1st digit at end etc..
        if (!IsPrime(a))
        {
            return false;
        }

        string b = a.ToString();
        for (int i = 0; i < b.Length; i++)
        {
            int digitAtStart = Convert.ToInt32(b.Substring(0, 1));
            b = b.Substring(1) + digitAtStart;
            if (!IsPrime(Convert.ToInt32(b)))
            {
                return false;
            }
        }

        return true;
    }

    public static bool IsPrime(int a)
    {
        if (a == 1)
        {
            return false;
        }
        for (int i = 2; i <= Math.Sqrt(a); i++)
        {
            if (a % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}
| | # 
( Euler )
[TestFixture]
public class E34Tests
{
    [Test]
    public void Factorial_Given2_Return1()
    {
        int result = E34.Factorial(2);
        Assert.AreEqual(2, result);
    }

    [Test]
    public void Factorial_Given3_Return6()
    {
        int result = E34.Factorial(3);
        Assert.AreEqual(6, result);
    }

    [Test]
    public void Factorial_Given4_Return24()
    {
        int result = E34.Factorial(4);
        Assert.AreEqual(24, result);
    }

    [Test]
    //testing arithmetic overflow
    public void Factorial_Given99999_Return24()
    {
        int result = E34.Factorial(99999);
        Assert.AreEqual(24, result);
    }

    [Test]
    public void IsCuriousNumber_Given145_ReturnTrue()
    {
        bool result = E34.IsCuriousNumber(145);
        Assert.IsTrue(result);
    }

    [Test]
    public void IsCuriousNumber_Given146_ReturnFalse()
    {
        bool result = E34.IsCuriousNumber(146);
        Assert.IsFalse(result);
    }

    [Test]
    public void FindSumOfAllCuriousNumbers_GivenNothing_ReturnAnswer()
    {
        int result = E34.FindSumOfAllCuriousNumbers();
        Assert.AreEqual(40730, result);
    }
}

public class E34
{
    public static int FindSumOfAllCuriousNumbers()
    {
        int total = 0;
        for (int i = 3; i < 10000000; i++)
        {
            if (IsCuriousNumber(i))
            {
                total += i;
                Console.WriteLine("{0:N0}", i);
            }
        }
        return total;
    }

    public static bool IsCuriousNumber(int a)
    {
        string b = a.ToString();
        int total = 0;
        for (int i = 0; i < b.Length; i++)
        {
            int digit = Convert.ToInt32(b.Substring(i, 1));
            total += Factorial(digit);
        }

        if (total == a)
        {
            return true;
        }
        return false;
    }

    public static int Factorial(int number)
    {
        int total = 1;
        for (int i = number; i > 1; i--)
        {
            total *= i;
        }
        return total;
    }
}
| | # 
( Euler )
[TestFixture]
    public class E33Tests
    {
        [Test]
        public void IsNonTrivialFraction_Given49x98_True()
        {
            bool result = E33.IsNonTrivialFraction(49, 98);
            Assert.IsTrue(result);
        }

        [Test]
        public void IsNonTrivialFraction_Given39x98_False()
        {
            bool result = E33.IsNonTrivialFraction(39, 98);
            Assert.IsFalse(result);
        }

        [Test]
        public void IsNonTrivialFraction_Given30x50_False()
        {
            bool result = E33.IsNonTrivialFraction(30, 50);
            Assert.IsFalse(result);
        }

        [Test]
        public void GetNonTrivialFractions_GivenNothing_ListOfAnswers()
        {
            List<List<int>> result = E33.GetNonTrivialFractions();
            Assert.AreEqual(4, result.Count);
        }

        [Test]
        public void ProductOfFractions_GivenNothing_ReturnFraction()
        {
            List<int> result = E33.ProductOfFractions();
            Assert.AreEqual(2, result.Count);

            //387296
            //38729600
        }

    }

    public class E33
    {
        public static List<int> ProductOfFractions()
        {
            List<List<int>> result = GetNonTrivialFractions();
            //multiple all numerators
            var numerators = new List<int>();
            var denominators = new List<int>();
            foreach (List<int> fractionList in result)
            {
                int numerator = fractionList[0];
                int denominator = fractionList[1];
                numerators.Add(numerator);
                denominators.Add(denominator);
            }

            int numeratorTotal = 1;
            int denominatorTotal = 1;
            foreach (int numerator in numerators)
            {
                numeratorTotal *= numerator;
            }

            //multiply all denominators
            foreach (int denominator in denominators)
            {
                denominatorTotal *= denominator;
            }

            //find lowest common term
            return new List<int>() {numeratorTotal, denominatorTotal};
        }

        public static List<List<int>> GetNonTrivialFractions()
        {
            var list = new List<List<int>>();
            for (int i = 10; i < 100; i++)
            {
                for (int j = 10; j < 100; j++)
                {
                    if (i != j)
                    {
                        if (i < j)
                        {
                            bool result = IsNonTrivialFraction(i, j);
                            if (result)
                            {
                                List<int> x = new List<int>() {i, j};
                                list.Add(x);
                            }
                        }
                    }
                }
            }
            return list;
        }

        public static bool IsNonTrivialFraction(int a, int b)
        {
            //does a number appear on the top and bottom?
            int firstTopDigit = Convert.ToInt32(a.ToString().Substring(0, 1));
            int secondTopDigit = Convert.ToInt32(a.ToString().Substring(1, 1));

            int firstBottomDigit = Convert.ToInt32(b.ToString().Substring(0, 1));
            int secondBottomDigit = Convert.ToInt32(b.ToString().Substring(1, 1));

            //if we take that number away on top and bottom
            //does it make the same fraction?
            int newTop = 0;
            int newBottom = 0;

            //trivial
            if ((secondTopDigit == 0) && (secondBottomDigit == 0))
            {
                return false;
            }

            if (firstTopDigit == firstBottomDigit)
            {
                newTop = secondTopDigit;
                newBottom = secondBottomDigit;
            }

            else if (firstTopDigit == secondBottomDigit)
            {
                newTop = secondTopDigit;
                newBottom = firstBottomDigit;
            }

            else if (secondTopDigit == firstBottomDigit)
            {
                newTop = firstTopDigit;
                newBottom = secondBottomDigit;
            }

            else if (secondTopDigit == secondBottomDigit)
            {
                newTop = firstTopDigit;
                newBottom = firstBottomDigit;
            }
            else //not curious
            {
                return false;
            }

            if (newBottom == 0)
            {
                return false;
            }

            int oldFraction = a * 1000 / b * 1000;
            int newFraction = newTop * 1000 / newBottom * 1000;

            if (oldFraction == newFraction)
            {
                return true;
            }
            return false;
        }
    }
| | # 
( Euler )

TDD doing well.

[TestFixture]
    public class E32Tests
    {
        [Test]
        public void IsPanDigital_GivenPDNumbers_ShouldReturnTrue()
        {
            bool result = E32.IsPandigital(39, 186, 7254);
            Assert.IsTrue(result);
        }

        [Test]
        public void IsPanDigital_GivenNonPDNumbersDouble_ShouldReturnFalse()
        {
            bool result = E32.IsPandigital(39, 286, 7254);
            Assert.IsFalse(result);
        }

        [Test]
        public void IsPanDigital_GivenNonPDNumbersTooFew_ShouldReturnFalse()
        {
            bool result = E32.IsPandigital(39, 86, 7254);
            Assert.IsFalse(result);
        }

        [Test]
        public void SumOfAllProductsPandigital_GivenNothing_ReturnAnswer()
        {
            int result = E32.SumOfAllProductsPandigital();
            Assert.AreEqual(45228, result);
        }
    }

    public class E32
    {
        public static int SumOfAllProductsPandigital()
        {
            var results = new List<int>();
            for (int i = 1; i < 5000; i++)
            {
                for (int j = 1; j < 5000; j++)
                {
                    int product = i*j;
                    if (IsPandigital(i, j, product))
                    {
                        if (!results.Contains(product))
                        {
                            results.Add(product);
                        }
                    }
                }
            }

            int result = 0;
            foreach (int i in results)
            {
                result += i;
            }
            return result;
        }

        public static bool IsPandigital(int a, int b, int c)
        {
            var found = new List<int>();
            bool panDigital = true;

            string number = a.ToString();
            GetValue(found, number);

            number = b.ToString();
            GetValue(found, number);

            number = c.ToString();
            GetValue(found, number);

            for (int i = 1; i < 10; i++)
            {
                if (found.Count != 9)
                {
                    return false;
                }
                if(!found.Contains(i))
                {
                    return false;
                }
            }

            return true;
        }

        private static void GetValue(List<int> found, string number)
        {
            for (int i = 0; i < number.Length; i++)
            {
                int digit = Convert.ToInt32(number.Substring(i, 1));
                found.Add(digit);
            }
        }
    }

| | # 
( Euler )

Tried this problem and found my 1st try became too complex, so backed out (with extensive working tests) and tried these approaches:

I liked this solution for simplicity: http://locationcube.blogspot.com/2010/12/euler-problem-31.html

Then the dynamic programming solution from http://www.mathblog.dk/project-euler-31-combinations-english-currency-denominations/

Dynamic programming – breaking down a problem into smaller sub-problems.

[TestFixture]
public class E31Tests
{
    [Test]
    public void HowManyWaysToMake_Given3Pence_Return2DifferentWays()
    {
        int result = E31.HowManyWaysToMake(3);
        Assert.AreEqual(2, result);
    }


    /* 1111
       211
       22 */
    [Test]
    public void HowManyWaysToMake_Given4Pence_Return3DifferentWays()
    {
        int result = E31.HowManyWaysToMake(4);
        Assert.AreEqual(3, result);
    }


    /* 11111
       2111
       221
       5 */
    [Test]
    public void HowManyWaysToMake_Given5Pence_Return4DifferentWays()
    {
        int result = E31.HowManyWaysToMake(5);
        Assert.AreEqual(4, result);
    }

    /* 111111
       21111
       2211
       222
       51 */
    [Test]
    public void HowManyWaysToMake_Given6Pence_Return5DifferentWays()
    {
        int result = E31.HowManyWaysToMake(6);
        Assert.AreEqual(5, result);
    }

    /* 1111111
       211111
       22111
       2221
       511
       52 */
    [Test]
    public void HowManyWaysToMake_Given7Pence_Return6DifferentWays()
    {
        int result = E31.HowManyWaysToMake(7);
        Assert.AreEqual(6, result);
    }

    /* 11111111
       2111111
       221111
       22211
       2222
       5111
       521
       */
    [Test]
    public void HowManyWaysToMake_Given8Pence_Return6DifferentWays()
    {
        int result = E31.HowManyWaysToMake(8);
        Assert.AreEqual(7, result);
    }

    /* 111111111
       21111111
       2211111
       222111
       22221
       51111
       5211
       522
       */
    [Test]
    public void HowManyWaysToMake_Given9Pence_Return6DifferentWays()
    {
        int result = E31.HowManyWaysToMake(9);
        Assert.AreEqual(8, result);
    }


    /* 1111111111
       211111111
       22111111
       2221111
       222211
       22222
       511111
       52111
       5221
       55
       10
       */
    [Test]
    public void HowManyWaysToMake_Given10Pence_Return6DifferentWays()
    {
        int result = E31.HowManyWaysToMake(10);
        Assert.AreEqual(11, result);
    }

    /* 11111111111
       2111111111
       221111111
       22211111
       2222111
       222221
       5111111
       521111
       52211
       5222
       551
       10 1
       */
    [Test]
    public void HowManyWaysToMake_Given11Pence_Return12DifferentWays()
    {
        int result = E31.HowManyWaysToMake(11);
        Assert.AreEqual(12, result);
    }

    [Test]
    public void HowManyWaysToMake_Given1Pence_ReturnAnswer()
    {
        int result = E31.HowManyWaysToMake(1);
        Assert.AreEqual(1, result);
    }

    [Test]
    public void HowManyWaysToMake_Given3Pence_ReturnAnswer()
    {
        int result = E31.HowManyWaysToMake(3);
        Assert.AreEqual(2, result);
    }

    [Test]
    public void HowManyWaysToMake_Given4Pence_ReturnAnswer()
    {
        int result = E31.HowManyWaysToMake(4);
        Assert.AreEqual(3, result);
    }

    [Test]
    public void HowManyWaysToMake_Given200Pence_ReturnAnswer()
    {
        int result = E31.HowManyWaysToMake(200);
        Assert.AreEqual(73682, result);
    }
}

public class E31
{
    public static int HowManyWaysToMake(int penceTarget)
    {
        int[] array = { 1, 2, 5, 10, 20, 50, 100, 200 };
        int[] ways = new int[penceTarget + 1];
        ways[0] = 1;
        //building up all solutions in the array
        for (int coinValue = 0; coinValue < array.Length; coinValue++)
        {
            //start with coinValue 1 pence which will give us 200 ways
            //ways[1] will always be 1 as only 1pence
            //ways[2] will be 2... as 11 and 2pence
            //ways[3] will be 2... 111,21
            //ways[4] will be 3 ... 1111,211,22
            for (int j = array[coinValue]; j <= penceTarget; j++)
            {
                //for higher values, uses lower values in array to add
                //see maths logic in article
                ways[j] += ways[j - array[coinValue]];
            }
            var x = 1;
        }

        return ways[penceTarget];
    }

    public static int HowManyWaysToMakeX(int pence)
    {
        int total = 0;

        for (int p1 = 0; p1 < 201; p1++)
        {
            for (int p2 = 0; p2 < 201; p2 += 2)
            {
                for (int p5 = 0; p5 < 201; p5 += 5)
                {
                    for (int p10 = 0; p10 < 201; p10 += 10)
                    {
                        for (int p20 = 0; p20 < 201; p20 += 20)
                        {
                            for (int p50 = 0; p50 < 201; p50 += 50)
                            {
                                for (int p100 = 0; p100 < 201; p100 += 100)
                                {
                                    if (p1 + +p2 + p5 + p10 + p20 + p50 + p100 == pence)
                                    {
                                        total++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        if (pence == 200)
        {
            total++;
        }
        return total;
    }
}

A good example here of solutions with a simple to understand brute force method, and a more logical way that needs greater explanation.

| | # 
# Monday, 25 June 2012
( Euler )

An interesting problem.  My solution turned out not to work, so turned to this solution:  http://locationcube.blogspot.com/2010/12/euler-problem-30.html

I like the way of getting digits. 

The Math.Pow method takes doubles as parameters which lead to this question on rounding errors:  http://stackoverflow.com/questions/11196700/math-pow-taking-an-integer-value

[TestFixture]
public class E30Tests
{
    [Test]
    public void SumOfNumbersOfPowersOfDigits_Given4_Return19316()
    {
        var result = E30.SumOfNumbersOfPowersOfDigits(4);
        Assert.AreEqual(19316, result);
    }

    [Test]
    public void SumOfNumbersOfPowersOfDigits_Given5_ReturnAnswer()
    {
        var result = E30.SumOfNumbersOfPowersOfDigits(5);
        Assert.AreEqual(443839, result);
    }
}

public class E30
{
    public static int SumOfNumbersOfPowersOfDigits(uint power)
    {
        int overallSum = 0;
        for (int i = 2; i <= 400000; i++)
        {
            string number = i.ToString();
            int sum = 0;
            for (int j = 0; j < number.Length; j++)
            {
                //get each number in main loop
                int digit = Convert.ToInt32(number.Substring(j, 1));
                //Math.Pow takes a double...doing an implicit converstion to double
                //sum += Convert.ToInt32(Math.Pow(digit, power));
                sum += IntPow(digit, power);
            }

            if (sum == i)
            {
                Console.WriteLine("{0:N0}",i);
                overallSum += sum;
            }

        }
        return overallSum;
    }

    public static int IntPow(int number, uint power)
    {
        int result = 1;
        for (int i = 0; i < power; i++)
        {
            result *= number;
        }
        return result;
    }

    //public static int IntPow(int x, uint pow)
    //{
    //    int ret = 1;
    //    while (pow != 0)
    //    {
    //        //unary operator.. logical AND
    //        if ((pow & 1) == 1)
    //            ret *= x;
    //        x *= x;
    //        pow >>= 1;
    //    }
    //    return ret;
    //}
}

 

image

and put on Arithmetic Overflow checking on.

| | # 
( Euler )

TDD and linq:

[TestFixture]
public class E29Tests
{
    [Test]
    public void DistinctTerms_GivenA2AndB5_Answer15()
    {
        var result = E29.DistinctTerms(2,5);
        Assert.AreEqual(15, result);
    }

    [Test]
    public void DistinctTerms_GivenA2AndB100_Answer()
    {
        var result = E29.DistinctTerms(2, 100);
        Assert.AreEqual(9183, result);
    }
}

public class E29
{
    public static int DistinctTerms(int a, int b)
    {
        var list = new List<BigInteger>();
        //rows
        for (int i = a; i <= b; i++)
        {
            //elements
            for (int k = a; k <= b; k++)
            {
                var number = (BigInteger)Math.Pow(i, k);
                list.Add(number);
                //Console.WriteLine("row {0} element {1} number {2}", i,k, number);
            }
        }
        int numberOfDistinctTerms = list.Distinct().Count();
        return numberOfDistinctTerms;
    }
}
| | # 
( Euler )

TDDing again and got the right answer first time.

[TestFixture]
public class E28Tests
{
    [Test]
    public void CreateSequence_GivenSpiralSize_ReturnArrayOfMoves()
    {
        var result = E28.CreateSequence(3);
        string[] array = new string[] { "r","d","l","l","u","u","r","r"};
        foreach (var s in result)
        {
            Console.WriteLine(s);
        }
        Assert.AreEqual(array, result);
    }

    [Test]
    public void BuildArray_Given3_ReturnCorrectArray()
    {
        int[,] result = E28.BuildArray(3);
        int[,] array = new int[,]
                           {
                               {7,8,9},
                               {6,1,2},
                               {5,4,3}
                           };
        Assert.AreEqual(array, result);
    }

    [Test]
    public void SumOfDiagonals_Given3_Return24()
    {
        int result = E28.SumOfDiagonals(3);
        Assert.AreEqual(25, result);
    }

    [Test]
    public void SumOfDiagonals_Given5_Return101()
    {
        int result = E28.SumOfDiagonals(5);
        Assert.AreEqual(101, result);
    }

    [Test]
    public void SumOfDiagonals_Given1001_ReturnAnswer()
    {
        int result = E28.SumOfDiagonals(1001);
        Assert.AreEqual(669171001, result);
    }

}

public class E28
{
    public static int SumOfDiagonals(int spiralSize)
    {
        int[,] array = BuildArray(spiralSize);
        int counter = 0;
        //top left to bottom right
        for (int i = 0; i < spiralSize; i++)
        {
            counter += array[i, i];
        }
        //top right to bottom left
        int rowCounter = 0;
        for (int i = spiralSize-1; i >= 0; i--)
        {
            counter += array[rowCounter, i];
            rowCounter++;
        }
        //take away the middle one which has been counted twice
        counter -= array[spiralSize/2, spiralSize/2];
        return counter;
    }
    public static string[] CreateSequence(int spiralSize)
    {
        int maxNumberOfMoves0Based = (spiralSize*spiralSize)-1;
        string[] array = new string[maxNumberOfMoves0Based];
        string currentDir = "r";
        int counter = 0;
        for (int i = 0; i < maxNumberOfMoves0Based; i++)
        {
            if (currentDir == "r")
            {
                counter++;
                for (int z = 1; z <= counter; z++)
                {
                    if (i == maxNumberOfMoves0Based)
                    {
                        break;
                    }
                    array[i] = "r";
                    i++;
                }
                i--;
                currentDir = "d";
            }
            else if (currentDir == "d")
            {
                for (int z = 1; z <= counter; z++)
                {
                    if (i == maxNumberOfMoves0Based)
                    {
                        break;
                    }
                    array[i] = "d";
                    i++;
                }
                i--;
                currentDir = "l";
            }
            else if (currentDir == "l")
            {
                counter++;
                for (int z = 1; z <= counter; z++)
                {
                    if (i == maxNumberOfMoves0Based)
                    {
                        break;
                    }
                    array[i] = "l";
                    i++;
                }
                i--;
                currentDir = "u";
            }
            else if (currentDir == "u")
            {
                for (int z = 1; z <= counter; z++)
                {
                    if (i == maxNumberOfMoves0Based)
                    {
                        break;
                    }
                    array[i] = "u";
                    i++;
                }
                i--;
                currentDir = "r";
            }
        }
        return array;
    }

    public static int[,] BuildArray(int spiralSize)
    {
        int[,] array = new int[spiralSize,spiralSize];
        string[] sequence = CreateSequence(spiralSize);
        int row = spiralSize/2;
        int column = spiralSize/2;
        int counter = 1;
        array[row, column] = counter;
        counter++;
        foreach (var command in sequence)
        {
            if (command == "r")
            {
                column++;
            }
            if (command == "d")
            {
                row++;
            }
            if (command == "l")
            {
                column--;
            }
            if (command == "u")
            {
                row--;
            }
            array[row, column] = counter;
            counter++;
        }
        return array;
    }
}

Another simpler approach here http://locationcube.blogspot.com/2010/12/euler-problem-28.html  seeing that that the matrix is acutally going up in multiples of 8 from different starting values.  Elegant.

| | # 
# Thursday, 14 June 2012
( Euler )
[TestFixture]
    public class E27Tests
    {
        [Test]
        public void IsPrime_GivenPrimesAndNonPrimes_ReturnAnswers()
        {
            Assert.AreEqual(true, E27.IsPrime(3));
            Assert.AreEqual(true, E27.IsPrime(5));
            Assert.AreEqual(true, E27.IsPrime(7));
            Assert.AreEqual(true, E27.IsPrime(11));
            Assert.AreEqual(true, E27.IsPrime(17));
            Assert.AreEqual(true, E27.IsPrime(23));
            Assert.AreEqual(false, E27.IsPrime(4));
            Assert.AreEqual(false, E27.IsPrime(10));
            Assert.AreEqual(false, E27.IsPrime(15));
            Assert.AreEqual(false, E27.IsPrime(20));
        }

        [Test]
        public void NumberOfPrimes_Given1And41_Return40()
        {
            int numberOfPrimes = E27.NumberOfPrimes(1, 41);
            Assert.AreEqual(40, numberOfPrimes);
        }

        [Test]
        public void NumberOfPrimes_GivenMinus79And1601_Return80()
        {
            int numberOfPrimes = E27.NumberOfPrimes(-79, 1601);
            Assert.AreEqual(80, numberOfPrimes);
        }

        [Test]
        //this is the answer
        public void NumberOfPrimes_GivenMinus61And97_Return62()
        {
            int numberOfPrimes = E27.NumberOfPrimes(-61, 971);
            Assert.AreEqual(71, numberOfPrimes);
        }

        [Test]
        public void MaxNumberOfPrimes_GivenNothing_Returnanswer()
        {
            int result = E27.MaxNumberOfPrimes();
            Assert.AreEqual(71, result);
        }

    }

    public class E27
    {
        public static int MaxNumberOfPrimes()
        {
            int maxA = 0;
            int maxB = 0;
            int largestNumberOfPrimes = 0;
            for (int a = -1000; a < 1000; a++)
            {
                for (int b = -1000; b < 1000; b++)
                {
                    var result = NumberOfPrimes(a, b);
                    if (result > largestNumberOfPrimes)
                    {
                        largestNumberOfPrimes = result;
                        maxA = a;
                        maxB = b;
                    }
                }
            }
            return largestNumberOfPrimes;
        }

        public static int NumberOfPrimes(int a, int b)
        {
            int countOfPrimes = 0;
            for (int i = 0; i < 10000; i++)
            {
                int result = Math.Abs((i * i) + (a * i) + b);
                if (IsPrime(result))
                {
                    countOfPrimes++;
                }
                else
                {
                    return countOfPrimes;
                }
            }
            return countOfPrimes;
        }

        public static bool IsPrime(int number)
        {
            //a number is prime if it can divide only by itself and 1 without a remainder
            for (int i = 2; i <= Math.Sqrt(number); i++)
            {
                if (number % i == 0)
                {
                    return false;
                }
            }
            return true;
        }
    }
    /*
     * Euler published the remarkable quadratic formula:

n? + n + 41

It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39.
     * However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly
     * when n = 41, 41? + 41 + 41 is clearly divisible by 41.

Using computers, the incredible formula  n? - 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79.
     * The product of the coefficients, -79 and 1601, is -126479.

Considering quadratics of the form:

n? + an + b, where |a|<1000 and |b|<1000

where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |-4| = 4
Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes
     * for consecutive values of n, starting with n = 0.
     */

Tricky due to Maths language of question.

| | # 
( Euler )
[TestFixture]
public class E26Tests
{
    [Test]
    public void FindRecurrance_GivenLongStringResultOf1Over7_ReturnLengthOfReccurance6()
    {
        var result = E26.FindRecurrance("14285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714285714");
        Assert.AreEqual(result, 6);
    }

    [Test]
    public void FindRecurrance_Given7_Return6()
    {
        BigInteger x = E26.GetRecurringCycle(7);
        var result = E26.FindRecurrance(x.ToString());
        Assert.AreEqual(6, result);
    }

    //17 gives us recurring at 16 places
    [Test]
    public void FindRecurrance_Given17_Return16()
    {
        BigInteger x = E26.GetRecurringCycle(17);
        var result = E26.FindRecurrance(x.ToString());
        Assert.AreEqual(16, result);
    }

    [Test]
    public void PrintRecurringCyclesToConsole_GivenNothing_ReturnAllFrom1To1000ToScreen()
    {
        var result = E26.PrintRecurringCycle();
        int count = 1;
        foreach (BigInteger number in result)
        {
            Console.WriteLine("{0}: {1}", count, number);
            count++;
        }
        CollectionAssert.IsNotEmpty(result);
    }

    [Test]
    public void FindLongestRecurringCycle_GiveNothing_ReturnResult()
    {
        var result = E26.FindLongestRecurringCycleBelow1000();
        Assert.AreEqual(983, result);
    }

    [Test]
    public void FindRecurrance_Given983_Return982()
    {
        BigInteger x = E26.GetRecurringCycle(983);
        var result = E26.FindRecurrance(x.ToString());
        Assert.AreEqual(982, result);
    }
}

public class E26
{
    public static int FindLongestRecurringCycleBelow1000()
    {
        int numberOfDigitsOfLongestRecurrance = 0;
        int denominatorOfLongestRecurrance = 0;
        for (int d = 2; d < 1000; d++)
        {
            BigInteger bigNumber = E26.GetRecurringCycle(d);
            int numberOfDigitsOfReccurrance = E26.FindRecurrance(bigNumber.ToString());
            //Console.WriteLine("d:{0}, numberOfDigitsOfReccurrance: {1}, number:{2}", d, numberOfDigitsOfReccurrance, bigNumber.ToString());
            if (numberOfDigitsOfReccurrance >= numberOfDigitsOfLongestRecurrance)
            {
                numberOfDigitsOfLongestRecurrance = numberOfDigitsOfReccurrance;
                denominatorOfLongestRecurrance = d;
            }
        }
        BigInteger bigNumber2 = E26.GetRecurringCycle(denominatorOfLongestRecurrance);
        int numberOfDigitsOfReccurrance2 = E26.FindRecurrance(bigNumber2.ToString());
        Console.WriteLine("i:{0}, occurranceLength: {1}, number:{2}", denominatorOfLongestRecurrance, numberOfDigitsOfReccurrance2, bigNumber2.ToString());
        return denominatorOfLongestRecurrance;
    }

    public static int FindRecurrance(string s)
    {
        //make chunks doubled up so as they 'repeat'
        string[] array = new string[(s.Length / 2) - 1];
        for (int i = 0; i < (s.Length / 2) - 1; i++)
        {
            array[i] = s.Substring(0, i + 1);
            array[i] += s.Substring(0, i + 1);
        }

        //problem here is for lower numbers need to check for for lower group lengths
        //but then on higher numbers then chances of finding that group length will give false postives
        //3 gives all tests passing
        for (int i = 3; i < array.Length; i++)
        {
            //if contains the chunk doubled up
            if (s.Contains(array[i]))
            {
                return i + 1;
            }
        }
        return 0;
    }

    public static IEnumerable PrintRecurringCycle()
    {
        IList<BigInteger> list = new List<BigInteger>();

        for (int i = 1; i <= 1000; i++)
        {
            var result = GetRecurringCycle(i);
            //Console.WriteLine("i: {0} number: {1}", i, result);
            list.Add(result);
        }
        return list;
    }

    public static BigInteger GetRecurringCycle(int denominator)
    {
        BigInteger number = 0;
        var x = BigInteger.Pow(10, 2000);
        number = x / denominator;
        return number;
    }
}

/*
 * A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2    =     0.5
1/3    =     0.(3)
1/4    =     0.25
1/5    =     0.2
1/6    =     0.1(6)
1/7    =     0.(142857)
1/8    =     0.125
1/9    =     0.(1)
1/10    =     0.1
Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d<1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.
 */

This had a tricky bug in it.. important to:

  • have test cases with higher numbers in it (was getting false positives)
  • have more test cases
  • have quick feedback cycles (NCrunch good for this)
  • put comments in more complex pieces of code and name variables well
| | # 
# Wednesday, 13 June 2012
( Euler )
    [TestFixture]
    public class E25Tests
    {
        [Test]
        public void FirstFibSeqToContain_Given3_Return12thTerm()
        {
            var result = E25.FirstFibSeqToContainDigits(3);
            Assert.AreEqual(12, result);
        }

        [Test]
        public void FirstFibSeqToContain_Given4_ReturnTerm()
        {
            var result = E25.FirstFibSeqToContainDigits(4);
            Assert.AreEqual(17, result);
        }

        [Test]
        public void FirstFibSeqToContain_Given5_ReturnTerm()
        {
            var result = E25.FirstFibSeqToContainDigits(5);
            Assert.AreEqual(21, result);
        }

        [Test]
        public void FirstFibSeqToContain_Given1000_ReturnTerm()
        {
            var result = E25.FirstFibSeqToContainDigits(1000);
            Assert.AreEqual(4782, result);
        }

    }

    public class E25
    {
        public static int FirstFibSeqToContainDigits(int numberOfDigitsRequired)
        {
            int numberInSequence = 2;
            BigInteger oldFib = 1;
            BigInteger newFib = 1;
            BigInteger currentFib = 0;
            int numberOfDigitsInCurrentFib = currentFib.ToString().Count();
            while (numberOfDigitsInCurrentFib != numberOfDigitsRequired)
            {
                currentFib = oldFib + newFib;
                oldFib = newFib;
                newFib = currentFib;
                numberInSequence++;
                numberOfDigitsInCurrentFib = currentFib.ToString().Count();
            }
            return numberInSequence;
        }
    }
    /*
     * The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:

F1 = 1
F2 = 1 oldFib
F3 = 2 newFib          oldFib
F4 = 3 currentFib      newFib
F5 = 5                 currentFib
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?
     */

using BigInteger in C#

| | # 
( Euler )

[TestFixture]
    public class E24Tests
    {
        [Test]
        public void ReturnAllPermutations_Given012_ReturnAll6Permutations()
        {
            IList<long> result = E24.ReturnAllPermutations(6, "012");
            CollectionAssert.IsNotEmpty(result);
            Assert.AreEqual(6, result.Count);
        }

        [Test]
        public void ReturnAllPermutations_Given0123_ReturnAll6Permutations()
        {
            IList<long> result = E24.ReturnAllPermutations(24, "0123");
            CollectionAssert.IsNotEmpty(result);
            Assert.AreEqual(24, result.Count);
        }

        [Test]
        //012   021   102   120   201   210
        public void ReturnPermutation_Given012_Return120()
        {
            var result = E24.ReturnPermutation(4, "012");
            Assert.AreEqual(120, result);
        }

        [Test]
        public void ReturnPermutation_Given01234_Ret1342()
        {
            var result = E24.ReturnPermutation(4, "01234");
            Assert.AreEqual(1342, result);
        }

        //[Test]
        //public void ReturnPermutation_Given01234_Ret13424()
        //{
        //    //                                        2300000000 takes 10 mins?
        //    var result = E24.ReturnPermutation(1000000, "0123456789");
        //    Assert.AreEqual(2783915460, result);
        //}
    }

    public class E24
    {
        public static long ReturnPermutation(int permutationToReturn, string digitsAsString)
        {
            IList<long> listOfAllPermutations = ReturnAllPermutations(permutationToReturn, digitsAsString);
            var result = listOfAllPermutations[permutationToReturn - 1];
            return result;
        }

        public static IList<long> ReturnAllPermutations(int permutationToReturn, string digits)
        {
            var permutations = new List<long>();
            int numberOfDigits = (int)digits.Count();
            string x = "";
            for (int i = 1; i <= numberOfDigits; i++)
            {
                x += "9";
            }
            long maxValue = 0;
            long.TryParse(x, out maxValue);

            long startNumber = 0;
            long.TryParse(digits, out startNumber);

            for (long i = startNumber; i < maxValue; i++)
            {
                //prepend with 0's if not max length
                int numberOfDigitsFori = (int)i.ToString().Count();
                int numberOfZerosToAdd = numberOfDigits - numberOfDigitsFori;
                string iAsString = i.ToString();
                for (int j = 1; j <= numberOfZerosToAdd; j++)
                {
                    iAsString = "0" + iAsString;
                }

                bool containsAllDigits = true;
                //if i contains each digit then add to list
                foreach (char digit in digits)
                {
                    string digitAsString = digit.ToString();
                    if (!iAsString.Contains(digitAsString))
                    {
                        containsAllDigits = false;
                        break;
                    }
                }
                if (containsAllDigits)
                {
                    permutations.Add(i);
                    int z = permutations.Count;
                    Console.WriteLine(z);
                    if (z == permutationToReturn)
                    {
                        return permutations;
                    }
                }
            }
            return null;
        }
    }
    /*
* A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4.
  If all of the permutations are listed numerically or alphabetically, we call it lexicographic order.
  The lexicographic permutations of 0, 1 and 2 are:
    012   021   102   120   201   210
    What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
  */

Took around 40mins to get answer in release mode with a Console app project.

static void Main(string[] args)
 {
     Stopwatch stopwatch = new Stopwatch();
     stopwatch.Start();

     var result = E24.ReturnPermutation(1000000, "0123456789");
     Console.WriteLine("result is {0}", result.ToString());
     stopwatch.Stop();
     Console.WriteLine("time taken: {0}", stopwatch.Elapsed);
 }

First try of doing it and got correct answer. Good TDD.

| | # 
# Saturday, 09 June 2012
( Euler )

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less thann and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

I solved this in a much different way than:

http://www.mathblog.dk/project-euler-23-find-positive-integers-not-sum-of-abundant-numbers/

I basically wrote a function:  CanBeWrittenAsASumOf2Abundantnumbers

then called that from 1 to 28123 times.

It took 11minutes and 33secs to run (compared to 110ms of his version).    So he basically uses a Sieve. 

[TestFixture]
public class E23Tests
{
    [Test]
    public void IsAbundant_Given12_ReturnTrue()
    {
        bool result = E23.IsAbundantNumber(12);
        Assert.IsTrue(result);
    }

    [Test]
    public void GetAllAbundantNumbersUnder_Given12_Return12()
    {
        List<int> result = E23.GetAllAbundantNumbersUnder(13);
        CollectionAssert.Contains(result, 12);
    }

    [Test]
    public void CanBeWrittenAsSumOf2AbundantNumbers_Given24_ReturnTrue()
    {
        E23.MakeAbundantNumbers();
        bool result = E23.CanBeWrittenAsSumOf2AbundantNumbers(24);
        Assert.IsTrue(result);
    }

    [Test]
    public void MakeAbundantNumbers_GivenNothing_ReturnAbundantNumbersListOfInts()
    {
        E23.MakeAbundantNumbers();
        IEnumerable<int> result = E23.AllAbundantNumbers;
        CollectionAssert.IsNotEmpty(result);
    }

    [Test]
    public void Solve_GivenNothing_GetAnswer()
    {
        int result = E23.Solve();
        Assert.AreEqual(411, result);
    }
}

public class E23
{
    public static IEnumerable<int> AllAbundantNumbers { get; set; }
    //for all numbers between 1 and 28123
    //find which cannot be written as the sum of two abundant numbers
    public static int Solve()
    {
        E23.MakeAbundantNumbers();
        int sum = 0;
        //28123
        for (int i = 1; i < 2000; i++)
        {
            if (!CanBeWrittenAsSumOf2AbundantNumbers(i))
            {
                sum += i;
                Console.WriteLine("i: {0}", i);
            }
        }
        return sum;
    }

    public static void MakeAbundantNumbers()
    {
        IEnumerable<int> listOfAbundantNumbers = GetAllAbundantNumbersUnder(28123);
        AllAbundantNumbers = listOfAbundantNumbers;
    }

    public static bool CanBeWrittenAsSumOf2AbundantNumbers(int number)
    {
        //only try the abundant numbers which are less than the number-11 (as the first abundant number is 12)
        IEnumerable<int> listOfAbundantNumbers = AllAbundantNumbers.Where(x => x < number-11);
        
        foreach (int i in listOfAbundantNumbers)
        {
            //reverse the order?
            var listOfAbundantNumbers2 = new List<int>(listOfAbundantNumbers);//.Where(x => x < number-i+1).OrderByDescending(x => x);
            foreach (var j in listOfAbundantNumbers2)
            {
                if ((i + j) == number)
                {
                    return true;
                }
            }
        }
        return false;
    }

    public static List<int> GetAllAbundantNumbersUnder(int number)
    {
        //isAbundant if the sum exceeds n
        var listOfAbundantNumbers = new List<int>();
        for (int i = 12; i < number; i++)
        {
            if (IsAbundantNumber(i))
            {
                listOfAbundantNumbers.Add(i);
            }
        }
        return listOfAbundantNumbers;
    }

    public static bool IsAbundantNumber(int number)
    {
        int sum = 0;
        for (int i = 1; i < number - 1; i++)
        {
            if (number % i == 0)
            {
                sum += i;
            }
        }
        if (sum > number)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public static bool IsPerfectNumber(int number)
    {
        int sum = 0;
        for (int i = 1; i < number-1; i++)
        {
            if (number % i == 0)
            {
                sum += i;
            }
        }
        if (sum == number)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
| | # 
( Euler )
    [TestFixture]
    public class E22Tests
    {
        [Test]
        public void LoadFile_CallMethod_ReturnFileAsListOfStrings()
        {
            List<string> result = E22.LoadFile();
            Assert.AreEqual(5163, result.Count);
        }

        [Test]
        public void AlphabeticalValueMultiplyByPosition_GivenColin_Return49714()
        {
            int result = E22.AlphabeticalValueMultiplyByPosition("COLIN");
            Assert.AreEqual(49714, result);
        }

        [Test]
        public void Solve_GivenNothing_GetAnswer()
        {
            var result = E22.Solve();
            Assert.AreEqual(1, result);
        }
    }

    public class E22
    {
        public static int Solve()
        {
            var listOfNames = LoadFile();
            listOfNames.Sort();
            int sum = 0;
            foreach (string name in listOfNames)
            {
                sum += AlphabeticalValueMultiplyByPosition(name);
            }
            return sum;
        }

        public static List<string> LoadFile()
        {
            //eg "MARY","PATRICIA","LINDA"   all on one line
            string text = File.ReadAllText(@"e:\temp\names.txt");

            text = text.Replace("\"", "");
            string[] words = text.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            var listOfNames = new List<string>();
            foreach (string line in words)
            {
                listOfNames.Add(line);
            }
            return listOfNames;
        }

        public static int AlphabeticalValueMultiplyByPosition(string name)
        {
            List<string> listOfNames = LoadFile();
            listOfNames.Sort();
            //go over each character in name eg C is 3
            int sum = 0;
            foreach (char c in name.ToCharArray())
            {
                sum += Convert.ToInt32(c) - 64;
            }

            //find which position in the list eg COLIN is 938
            int positionInSortedList = listOfNames.IndexOf(name) + 1;

            return positionInSortedList*sum;
        }
    }
    /*
begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical
position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list.
So, COLIN would obtain a score of 938  53 = 49714.

What is the total of all the name scores in the file?
     * */
| | # 
# Friday, 08 June 2012
( Euler )
[TestFixture]
    public class E21Tests
    {
        [Test]
        public void SumOfProperDivisors_Given220_Return284()
        {
            int result = E21.SumOfProperDivisors(220);
            Assert.AreEqual(284, result);
        }

        [Test]
        public void SumOfProperDivisors_Given284_Return220()
        {
            int result = E21.SumOfProperDivisors(284);
            Assert.AreEqual(220, result);
        }

        [Test]
        public void FindAllAmicableNumbersUnder10000_GivenNothing_ReturnListOfAmicableNumbers()
        {
            List<int> result = E21.FindAllAmicableNumbersUnder10000();
            CollectionAssert.IsNotEmpty(result);
            var distinct = result.Distinct();
            //var distinct = result;
            int sum = 0;
            foreach (int number in distinct)
            {
                sum += number;
                Console.WriteLine(number);
            }
            Assert.AreEqual(31626, sum);
        }
    }

    public class E21
    {
        public static List<int> FindAllAmicableNumbersUnder10000()
        {
            var listOfInts = new List<int>();
            for (int i = 0; i <= 10000; i++)
            {
                //eg 220 will give 284 as result
                int result = SumOfProperDivisors(i);
                //284 as result will give 220 as result2
                int result2 = SumOfProperDivisors(result);
                // i != result   ie must be different numbers
                if (result2 == i && i != result)
                {
                    listOfInts.Add(i); //eg 220
                    listOfInts.Add(result); //eg 284
                }
            }
            return listOfInts;
        }

        public static int SumOfProperDivisors(int number)
        {
            var listOfDivisors = new List<int>();
            for (int i = 1; i < number; i++)
            {
                if (number % i == 0)
                {
                    listOfDivisors.Add(i);
                }
            }

            int sum = 0;
            foreach (int divisor in listOfDivisors)
            {
                sum += divisor;
            }
            return sum;
        }
| | # 
# Thursday, 07 June 2012
( Euler )
[TestFixture]
    public class Euler20FactorialTests
    {
        [Test]
        public void Factorial_Given10_Return3628800()
        {
            BigInteger result = Euler20Factorial.Factorial(10);
            BigInteger x = new BigInteger(3628800);
            Assert.AreEqual(x, result);
        }

        [Test]
        public void Sum_Given12345_ReturnSumOfDigits()
        {
            int result = Euler20Factorial.SumOfDigits(12345);
            Assert.AreEqual(15, result);
        }

        [Test]
        public void Sum_Given3628800_ReturnSumOfDigits()
        {
            int result = Euler20Factorial.SumOfDigits(3628800);
            Assert.AreEqual(27, result);
        }

        [Test]
        public void FactorialAndSumOfDigits_Given100_ReturnSumOfDigits()
        {
            int result = Euler20Factorial.FactorialAndSumOfDigits(100);
            Assert.AreEqual(648, result);
        }

    }

    public class Euler20Factorial
    {
        //For example, 10! = 10  9  ...  3  2  1 = 3628800,
        //and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
        //Find the sum of the digits in the number 100!
        public static int FactorialAndSumOfDigits(int number)
        {
            BigInteger result = Factorial(100);
            int sumOfDigits = SumOfDigits(result);
            return sumOfDigits;
        }

        public static BigInteger Factorial(BigInteger number)
        {
            for (BigInteger i = number - 1; i > 1; i--)
            {
                number = number * i;
            }
            return number;
        }

        public static int SumOfDigits(BigInteger number)
        {
            BigInteger sum = 0;
            while (number != 0)
            {
                //divides number by 10 and returns the remainder
                //ie 1234.5  (therefore 5 is remainder)
                //we loop over each remainder from the right hand side to the left
                BigInteger x = number%10;
                sum = sum + x;
                number = number / 10;
            }
            return (int)sum;
        }
    }

Good code for SumOfDigits from Greg: http://stackoverflow.com/questions/478968/sum-of-digits-in-c-sharp

| | # 
( Euler )
[TestFixture]
    public class Euler19DateTests
    {
        [Test]
        public void GetAnswer_GivenNothing_ReturnAnswer()
        {
            var result = Euler19Dates.GetAnswer();
            Assert.AreEqual(171, result);
        }
    }

    public class Euler19Dates
    {
        //How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

        //1 Jan 1900 was a Monday.
        //Thirty days has September,
        //April, June and November.
        //All the rest have thirty-one,
        //Saving February alone,
        //Which has twenty-eight, rain or shine.
        //And on leap years, twenty-nine.
        //A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
        public static int GetAnswer()
        {
            int countOfSundaysOnFirstOfMonth = 0;

            var StartDate = new DateTime(1901, 1, 1);
            StartDate = StartDate.AddDays(-1);
            var EndDate = new DateTime(2000, 12, 31);

            //make a list of all dates
            var dateList = new List<DateTime>();
            while (StartDate.AddDays(1) <= EndDate)
            {
                StartDate = StartDate.AddDays(1);
                dateList.Add(StartDate);
            }

            foreach (var date in dateList)
            {
                if ((date.DayOfWeek == DayOfWeek.Sunday) && (date.Day == 1))
                {
                    countOfSundaysOnFirstOfMonth++;
                }
            }
            return countOfSundaysOnFirstOfMonth;
        }
    }
| | # 
# Wednesday, 06 June 2012
( Euler )

Path through a triangle of numbers

[TestFixture]
public class ScratchTests
{
    [Test]
    public void MaximumTotalTopToBottomInTestTriangle_Go_ShouldReturn23()
    {
        int result = Scratch.GetAnswerForTestTriangle();
        Assert.AreEqual(23, result);
    }

    [Test]
    public void MaximumTotalTopToBottomInBigTriangle_Go_ShouldReturnAnwser()
    {
        int result = Scratch.GetAnswerForBigTriangle();
        Assert.AreEqual(23, result);
    }

    [Test]
    public void BuildArrayFromList_GivenData_GetArrayBackInFormatWeWant()
    {
        int[,] result = Scratch.BuildTestArrayFromList();
        Assert.AreEqual(3, result[0, 3]);
    }
}


public class Scratch
{
    public static int[,] BuildTestArrayFromList()
    {
        int[,] array = new int[4, 7];
        var listOfInts1 = new List<int>() { 3 };
        var listOfInts2 = new List<int>() { 7, 4 };
        var listOfInts3 = new List<int>() { 2, 4, 6 };
        var listOfInts4 = new List<int>() { 8, 5, 9, 3 };
        var listOfListOfInts = new List<List<int>>() { listOfInts1, listOfInts2, listOfInts3, listOfInts4 };
        int row = 0;
        int numberOfColumns = array.GetLength(1);
        int column = numberOfColumns / 2;
        foreach (List<int> list in listOfListOfInts)
        {
            int startingColumn = 0;
            foreach (int number in list)
            {
                if (startingColumn == 0)
                {
                    startingColumn = column;
                }
                array[row, column] = number;
                column = column + 2;
            }
            column = startingColumn - 1;
            row++;
        }
        return array;
    }

    private static int[,] BuildArrayFromList()
    {
        int[,] array = new int[15, 29];
        var listOfInts1 = new List<int>() { 75 };
        var listOfInts2 = new List<int>() { 95,64 };
        var listOfInts3 = new List<int>() { 17,47,82 };
        var listOfInts4 = new List<int>() { 18,35,87,10 };
        var x5 = new List<int>() { 20,04,82,47,65 };
        var x6 = new List<int>() { 19,01,23,75,03,34 };
        var x7 = new List<int>() { 88,02,77,73,07,63,67 };
        var x8 = new List<int>() { 99,65,04,28,06,16,70,92 };
        var x9 = new List<int>() { 41,41,26,56,83,40,80,70,33 };
        var x10 = new List<int>() {41,48,72,33,47,32,37,16,94,29};
        var x11 = new List<int>() {53,71,44,65,25,43,91,52,97,51,17};
        var x12 = new List<int>() {70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57};
        var x13 = new List<int>() {91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48};
        var x14 = new List<int>() {63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31};
        var x15 = new List<int>() {04, 62, 98, 27, 23, 09, 70, 98, 73, 93, 38, 53, 60, 04, 23};
        var listOfListOfInts = new List<List<int>>() { listOfInts1, listOfInts2, listOfInts3, listOfInts4,x5,x6,x7,x8,x9,x10,x11,x12,x13,x14,x15 };
        int row = 0;
        int numberOfColumns = array.GetLength(1);
        int column = numberOfColumns / 2;
        foreach (List<int> list in listOfListOfInts)
        {
            int startingColumn = 0;
            foreach (int number in list)
            {
                if (startingColumn == 0)
                {
                    startingColumn = column;
                }
                array[row, column] = number;
                column = column + 2;
            }
            column = startingColumn - 1;
            row++;
        }
        return array;
    }

    public static int GetAnswerForTestTriangle()
    {
        //4 rows, 7 'columns'
        //int[,] array = new int[4, 7];
        //array[0, 3] = 3;
        //array[1, 2] = 7;
        //array[1, 4] = 4;
        //array[2, 1] = 2;
        //array[2, 3] = 4;
        //array[2, 5] = 6;
        //array[3, 0] = 8;
        //array[3, 2] = 5;
        //array[3, 4] = 9;
        //array[3, 6] = 3;
        int[,] array = BuildTestArrayFromList();
        int result = Scratch.MaximumTotalInTriangle(array);
        return result;
    }

    public static int GetAnswerForBigTriangle()
    {
        int[,] array = BuildArrayFromList();
        int result = Scratch.MaximumTotalInTriangle(array);
        return result;
    }

    //recursion?
    //remember routes taken already? eg lrllr  for left right etc..
    public static int MaximumTotalInTriangle(int[,] array)
    {
        var random = new Random();
        //4 rows, 7 columns for testTriangle
        int numberOfRows = array.GetLength(0);
        int numberOfColumns = array.GetLength(1);

        int biggestSumSoFar = 0;
        for (int i = 0; i < 1000000; i++)
        {
            int sum = 0;
            //int column = 3; **could be an issue here
            int column = numberOfColumns / 2;

            for (int row = 0; row < numberOfRows; row++)
            {
                sum += array[row, column];

                //final row
                if (row != numberOfRows - 1)
                {
                    int rand = random.Next(1, 3);
                    if (rand == 1)
                    {
                        column--;
                    }
                    else
                    {
                        column++;
                    }
                }
            }
            if (sum > biggestSumSoFar)
            {
                biggestSumSoFar = sum;
            }
        }
        return biggestSumSoFar;
    }
}

better way of making a listOfLists by just adding lists straight away and not needing intermediate variables eg x1

http://stackoverflow.com/questions/10925261/adding-many-lists/10925616#10925616

Looks like a lot of people used recursion (a tree, so good fit).  And also used arrays instead of lists.

| | # 
# Tuesday, 05 June 2012
( Euler )

This was a good business case problem, as it required good testing!

[TestFixture]
public class Euler17Tests
{
    [Test]
    public void CountLetters_GivenFive_ReturnAnswerOf19Letters()
    {
        int result = Euler17.CountTotalLettersInEveryNumberUpTo(5);
        Assert.AreEqual(19, result);
    }

    [Test]
    public void CountLetters_GivenOneThousand_ReturnAnswer()
    {
        int result = Euler17.CountTotalLettersInEveryNumberUpTo(1000);
        Assert.AreEqual(21124, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOne_Return3()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(1);
        Assert.AreEqual(3, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(2);
        Assert.AreEqual(3, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(3);
        Assert.AreEqual(5, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(4);
        Assert.AreEqual(4, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(5);
        Assert.AreEqual(4, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(6);
        Assert.AreEqual(3, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(7);
        Assert.AreEqual(5, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(8);
        Assert.AreEqual(5, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(9);
        Assert.AreEqual(4, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(10);
        Assert.AreEqual(3, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(11);
        Assert.AreEqual(6, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(12);
        Assert.AreEqual(6, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(13);
        Assert.AreEqual(8, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(14);
        Assert.AreEqual(8, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(15);
        Assert.AreEqual(7, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(16);
        Assert.AreEqual(7, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(17);
        Assert.AreEqual(9, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(18);
        Assert.AreEqual(8, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(19);
        Assert.AreEqual(8, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(20);
        Assert.AreEqual(6, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(3);
        Assert.AreEqual(5, result);
    }
    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenTwentyOne_Return9()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(21);
        Assert.AreEqual(9, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenTwentyThree_Return11()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(23);
        Assert.AreEqual(11, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenTwentyFour_Return10()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(24);
        Assert.AreEqual(10, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenThirty_Return6()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(30);
        Assert.AreEqual(6, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenEighty_Return6()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(80);
        Assert.AreEqual(6, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenNinety_Return6()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(90);
        Assert.AreEqual(6, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenThirtyThree_Return11()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(33);
        Assert.AreEqual(11, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundred_Return10()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(100);
        Assert.AreEqual(10, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndTwo_Return16()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(102);
        Assert.AreEqual(16, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndEleven_Return19()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(111);
        Assert.AreEqual(19, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndThirteen_Return21()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(113);
        Assert.AreEqual(21, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndFifteen_Return20()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(115);
        Assert.AreEqual(20, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndTwenty_Return19()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(120);
        Assert.AreEqual(19, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndTwentyFour_Return23()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(124);
        Assert.AreEqual(23, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneHundredAndFiftyFive_Return22()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(155);
        Assert.AreEqual(22, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenThreeHundredAndFourtyTwo_Return23()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(342);
        Assert.AreEqual(23, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenThreeHundredAndFiftyFive_Return24()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(355);
        Assert.AreEqual(24, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenFivehundred_Return11()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(500);
        Assert.AreEqual(11, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenNineHundredAndNinetySeven_Return25()
    {
        //NineHundredAndNinety
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(990);
        Assert.AreEqual(20, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(991);
        Assert.AreEqual(23, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(992);
        Assert.AreEqual(23, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(993);
        Assert.AreEqual(25, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(994);
        Assert.AreEqual(24, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(995);
        Assert.AreEqual(24, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(996);
        Assert.AreEqual(23, result);
        result = Euler17.CountOfLettersInNumberWrittenInEnglish(997);
        Assert.AreEqual(25, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenNineHundredAndNinetyEight_Return25()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(998);
        Assert.AreEqual(25, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenNineHundredAndNinetyNine_Return24()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(999);
        Assert.AreEqual(24, result);
    }

    [Test]
    public void CountOfLettersInNumberWrittenInEnglish_GivenOneThousand_Return11()
    {
        int result = Euler17.CountOfLettersInNumberWrittenInEnglish(1000);
        Assert.AreEqual(11, result);
    }
}

public static class Euler17
{
    public static int CountTotalLettersInEveryNumberUpTo(int maxNumber)
    {
        int count = 0;
        for (int i = 1; i <= maxNumber; i++)
        {
            var result = CountOfLettersInNumberWrittenInEnglish(i);
            count += result;
            Console.WriteLine("i: {0} count of letters: {1}", i, result);
        }
        return count;
    }

    public static int CountOfLettersInNumberWrittenInEnglish(int i)
    {
        int result = 0;
        if (i <= 20)
        {
            return CountOfLettersBetweenOneAndTwenty(i);
        }

        if (i > 20 && i < 100)
        {
            //eg 20,30,40
            int baseTen = Convert.ToInt32(i.ToString().Substring(0, 1) + "0");
            i -= baseTen;
            result = CountOfLettersBetweenOneAndTwenty(i);
            result += CountOfLettersBaseForTwentyToNinety(baseTen);
            return result;
        }

        int baseTenx = Convert.ToInt32(i.ToString().Substring(1, 1));
        int baseZerox = Convert.ToInt32(i.ToString().Substring(2, 1));
        //if 100,200,300 etc
        if (i != 1000)
        {
            if (baseTenx == 0 && baseZerox == 0)
            {
                //get first number
                string a = i.ToString().Substring(0, 1);
                int baseNumber = int.Parse(a);

                result = CountOfLettersBetweenOneAndTwenty(baseNumber);
                //eg OneHundred
                return result + 7;
            }
        }

        if (i > 100 && i < 1000)
        {
            //eg 234 would be 2 as we know it will be less than 1000
            int firstDigit = i/100;
            //eg 234 would be 3
            int secondDigit = Convert.ToInt32(i.ToString().Substring(1, 1));

            //eg 200
            int baseHundred = Convert.ToInt32(i.ToString().Substring(0,1) + "0" + "0");

            //eg 30
            int baseTen = Convert.ToInt32(i.ToString().Substring(1,1) + "0");

            if (baseTen < 20)
            {
                result = CountOfLettersBetweenOneAndTwenty(i - baseHundred);
            }
            else
            {
                //342 would be 342-300.. 42-40 = 2
                int stage = (i - baseHundred) - baseTen;
                //eg for 124, we pass in 4
                result = CountOfLettersBetweenOneAndTwenty(stage);
                var stageb = CountOfLettersBaseForTwentyToNinety(baseTen);
                result += stageb;
            }

            //One HundredAnd
            result += CountOfLettersBetweenOneAndTwenty(firstDigit) + 10;
        }

        if (i == 1000)
        {
            result = 11;
        }

        return result;
    }

    private static int CountOfLettersBaseForTwentyToNinety(int baseNumber)
    {
        switch (baseNumber)
        {
            case 20:
                return 6;
            case 30:
                return 6;
            case 40:
                return 5;
            case 50:
                return 5;
            case 60:
                return 5;
            case 70:
                return 7;
            case 80:
                return 6;
            case 90:
                return 6;
        }
        return 0;
    }

    private static int CountOfLettersBetweenOneAndTwenty(int i)
    {
        switch (i)
        {
            case 1:
                {
                    return 3;
                }
            case 2:
                {
                    int countOfLettersInNumberWrittenInEnglish = 3;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 3:
                {
                    int countOfLettersInNumberWrittenInEnglish = 5;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 4:
                {
                    int countOfLettersInNumberWrittenInEnglish = 4;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 5:
                {
                    int countOfLettersInNumberWrittenInEnglish = 4;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 6:
                {
                    int countOfLettersInNumberWrittenInEnglish = 3;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 7:
                {
                    int countOfLettersInNumberWrittenInEnglish = 5;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 8:
                {
                    int countOfLettersInNumberWrittenInEnglish = 5;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 9:
                {
                    int countOfLettersInNumberWrittenInEnglish = 4;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 10:
                {
                    int countOfLettersInNumberWrittenInEnglish = 3;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 11:
                {
                    int countOfLettersInNumberWrittenInEnglish = 6;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 12:
                {
                    int countOfLettersInNumberWrittenInEnglish = 6;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 13:
                {
                    int countOfLettersInNumberWrittenInEnglish = 8;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 14:
                {
                    int countOfLettersInNumberWrittenInEnglish = 8;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 15:
                {
                    int countOfLettersInNumberWrittenInEnglish = 7;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 16:
                {
                    int countOfLettersInNumberWrittenInEnglish = 7;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 17:
                {
                    int countOfLettersInNumberWrittenInEnglish = 9;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 18:
                {
                    int countOfLettersInNumberWrittenInEnglish = 8;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 19:
                {
                    int countOfLettersInNumberWrittenInEnglish = 8;
                    return countOfLettersInNumberWrittenInEnglish;
                }
            case 20:
                {
                    int countOfLettersInNumberWrittenInEnglish = 6;
                    return countOfLettersInNumberWrittenInEnglish;
                }
        }
        return 0;
    }

A cleaner way to implement would be to build up the string in English, then do a word count.. this would mean it would be far easier to test as could dump out to the screen.

This was a very TDD way of implementing it.

| | # 
( Euler )
[TestFixture]
    public class Euler16bTests
    {
        [Test]
        public void Solve_Given15_Return26()
        {
            var result = Euler16b.SolveSumOfTheDigits(15);
            Assert.AreEqual(26, result);
        }

        [Test]
        public void Solve_Given1000_ReturnAnswer()
        {
            var result = Euler16b.SolveSumOfTheDigits(1000);
            Assert.AreEqual(1366, result);
        }

    }

    public static class Euler16b
    {
        public static int SolveSumOfTheDigits(int toThePowerOf)
        {
            double r = Math.Pow(2, toThePowerOf);
            BigInteger result = (BigInteger) r;
   
            string resultAsString = result.ToString();
            int sum = 0;
            for (int j = 0; j < resultAsString.Length; j++)
            {
                Char digitAsChar = resultAsString[j];
                String digitAsString = digitAsChar.ToString();
                int number = Convert.ToInt32(digitAsString);
                sum += number;
            }
            return sum;
        }
    }
| | # 
( Euler | Git | Resharper )

Am trying out using git now on every project - mainly so I can easily revert if I mess things up.  Good practice.

git init

git add .

git commit -m "first commit of Euler 15"

git checkout -b firsttry

git branch (to see branches)

gitgui

image

R# – Move to another file with same name

Forumla

http://locationcube.blogspot.co.uk/2010/12/project-eulerproblem-15.html

The formula is n! / r! (n-r)!

Where n is 40 and r is 20…  so 40!/(20! * 20!)

Which gives us:    137846528820 ways to get there!

In fact Google’s online calculator can do this for you….

Just type 40 choose 20 into Google!!

image

Discrete Mathematics

– on a 2*2 square it takes 4 steps to reach the end. So on a 20*20 square it takes 40 steps.

20 increases in x and 20 increases in y

how many different ways can you choose 20 elements out of a set of 40 elements.

We can use a formula to solve this. “n choose r formula”: N!/r!(n-r)

40!/((20!)(40-20)!)

N = number of elements (40)

r = how many we want to choose

137,846,528,820

Dynamic Programming

How many routes are there through a 20×20 grid? or.. total number of ways to arrive at a node?

dynamic programming is a method for solving complex problems by breaking them down into simpler subproblems

We find the total number of ways to arrive at a node:

“Sum of the count from above and to the left”

[TestFixture]
public class DynamicProgrammingTests
{
    private DynamicProgramming dynamicProgramming;

    [SetUp]
    public void DoFirst()
    {
        this.dynamicProgramming = new DynamicProgramming();
    }

    [Test]
    public void Four_DynamicProgrammingSolver_GivesAnswerOf70()
    {
        var result = dynamicProgramming.Solve(4);
        Assert.AreEqual(70, result);
    }

    [Test]
    public void Five_DynamicProgrammingSolver_GivesAnswerOf252()
    {
        var result = dynamicProgramming.Solve(5);
        Assert.AreEqual(252, result);
    }

    [Test]
    public void Twenty_DynamicProgrammingSolver_GivesAnswerOf252()
    {
        var result = dynamicProgramming.Solve(20);
        //137,846,528,820
        Assert.AreEqual(137846528820, result);
    }
}

//using property of problem that
//total number of ways to arrive at a node
//is count from left and above
//so we build an array with total number of ways to arrive at a node
public class DynamicProgramming
{
    public double Solve(int sizeOfGrid)
    {
        var array = new double[sizeOfGrid+2, sizeOfGrid+2];

        int i, j;
        array[1, 1] = 1;
        for (i = 1; i <= sizeOfGrid+1; i++)
        {
            for (j = 1; j <= sizeOfGrid+1; j++)
            {
                //count from left, then count from above
                array[i, j] += array[i - 1, j] + array[i, j - 1];
            }
        }
        double result = array[sizeOfGrid+1, sizeOfGrid+1];
        return result;
    }
}

put in photo here of array with answers in it.

Brute Force – Recursive

[TestFixture]
public class SolverTests
{
    private BruteForceRecursionSolver bruteForceRecursionSolver;
    [SetUp]
    public void DoThisAtStart()
    {
        this.bruteForceRecursionSolver = new BruteForceRecursionSolver();
    }
    [Test]
    public void TwoGivesAnswerOf6()
    {
        bruteForceRecursionSolver.gridSize = 2;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(6, result);
    }

    [Test]
    public void ThreeGivesAnswerOf20()
    {
        bruteForceRecursionSolver.gridSize = 3;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(20, result);
    }

    [Test]
    public void FourGivesAnswerOf70()
    {
        bruteForceRecursionSolver.gridSize = 4;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(70, result);
    }

    [Test]
    public void FiveGivesAnswerOf252()
    {
        bruteForceRecursionSolver.gridSize = 5;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(252, result);
    }

    [Test]
    public void TenGivesAnswerOf184756()
    {
        bruteForceRecursionSolver.gridSize = 10;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(184756, result);
    }

    [Test]
    public void ElevenGivesAnswerOf705432()
    {
        bruteForceRecursionSolver.gridSize = 11;
        var result = bruteForceRecursionSolver.Progress(0, 0);
        Assert.AreEqual(705432, result);
    }
}

//http://stackoverflow.com/questions/2200236/project-euler-15
public class BruteForceRecursionSolver
{
    public int gridSize;

    // top left is 0,0
    public int Progress(int x, int y)
    {
        int i = 0;

        if (x < gridSize)
            //favours going right
            i += Progress(x + 1, y);
        if (y < gridSize)
            i += Progress(x, y + 1);

        //reached bottom right
        if (x == gridSize && y == gridSize)
            return 1;
        return i;
    }
}

This is very much brute force..

This took about 1.5 hours:

public class SolveRecursion
    {
        public long Combination = 0;
        public int GridSize;

        public void CalculateCombination(int x = 0, int y = 0)
        {
            if (x < GridSize)
            {
                CalculateCombination(x + 1, y);
            }
            if (y < GridSize)
            {
                CalculateCombination(x, y + 1);
            }
            if (x == GridSize && y == GridSize)
                Combination++;
        }
    }
static void Main(string[] args)
        {
            //gives correct answer: 137,846,528,820
            Console.WriteLine("starting");
            Stopwatch stopWatch = new Stopwatch();
            stopWatch.Start();
            var solveRecursion2 = new SolveRecursion { GridSize = 20 };
            solveRecursion2.CalculateCombination();
            var result = solveRecursion2.Combination;
            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            Console.WriteLine("Result is: {0}, time was {1} seconds", result, ts.ToString());
        }

and non recursive thoughts on:

http://stackoverflow.com/questions/10890516/rewrite-recursive-algorithm-more-simply-euler-15

| | # 
# Wednesday, 04 April 2012
( Euler )

Sequence:

namespace Euler14
{
    public class Euler14Core
    {
        public List<double> ReturnTerms(double n)
        {
            var listOfTerms = new List<double> { n };
            var keepgoing = true;
            while (keepgoing)
            {
                double result = 0;
                //odd
                if (n % 2 != 0)
                    result = (3 * n) + 1;
                else
                    result = n / 2;
                listOfTerms.Add(result);
                if (result == 1)
                    keepgoing = false;
                if (result < 0)
                    Console.WriteLine("problem");
                n = result;
            }

            return listOfTerms;
        }

        public int ReturnNumberOfTerms(int i)
        {
            List<double> result = ReturnTerms(i);
            return result.Count();
        }

        public int ReturnAnswer()
        {
            int highestNumberOfTerms = 0;
            int whichStartingNumberGaveHighestNumberOfTerms = 0;
            for (int k = 2; k < 1000000; k++)
            {
                int current = 0;
                current = ReturnNumberOfTerms(k);
                if (current > highestNumberOfTerms)
                {
                    highestNumberOfTerms = current;
                    whichStartingNumberGaveHighestNumberOfTerms = k;
                    Debug.WriteLine("highest is now: " + highestNumberOfTerms);
                }
            }
            return whichStartingNumberGaveHighestNumberOfTerms;
        }
    }
}

code

namespace Euler14
{
    [TestFixture]
    public class Euler14CoreTests
    {
        private Euler14Core e;
        [SetUp]
        public void Euler14CoreTestsSetup()
        {
            e = new Euler14Core();
        }

        [Test]
        public void ReturnTerms_Given13_ShouldReturnAListOfIntsInSequence()
        {
            var result = e.ReturnTerms(13);
            var expected = new List<double>() { 13, 40, 20, 10, 5, 16, 8, 4, 2, 1 };
            CollectionAssert.AreEquivalent(expected, result);
            Debug.WriteLine("done");
        }

        [Test]
        public void ReturnNumberOfTerms_Given13_ShouldReturn10()
        {
            int result = e.ReturnNumberOfTerms(13);
            Assert.AreEqual(10, result);
        }

        //main test for getting answer
        [Test]
        public void ReturnAnswer_GivenNothing_ShouldReturnNumberWithMostTermsUnder1m()
        {
            int result = e.ReturnAnswer();
            Assert.AreEqual(837799, result);
        }

        //tests to get around int/double overflow of main algorithm having numbers
        //in sequence which are bigger than an int
        //113383 made the sequence go over an ints range
        //[Test]
        //public void ReturnTerms_Given113383_ShouldReturnAListOfIntsInSequence()
        //{
        //    var result = e.ReturnTerms(113383);
        //    var expected = new List<double>() { 1, 2, 3 };
        //    CollectionAssert.AreEquivalent(expected, result);
        //}
    }
}

tests

image

checking for overflow/underflow would have saved me a lot of time!

| | # 
# Sunday, 18 March 2012
( Euler )

My current goal is to do these TDD style so I can practice.

 

The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word.

Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?

http://projecteuler.net/thread=42;page=8  pzelnips explanation of the Maths is good.

[TestFixture]
    public class Euler42Tests
    {
        Euler42 e;

        [SetUp]
        public void Euler42TestsSetup()
        {
            e = new Euler42();
        }

        [Test]
        public void LoadTextFile_GivenWordsTxt_ShouldReturnAsACSVString()
        {
            string result = e.LoadWordsTxt();
            Assert.IsNotEmpty(result);
        }

        [Test]
        public void TakeOffQuotationMarks_GivenWordsTxt_ShouldReturnAsACleanCSVString()
        {
            string words = e.LoadWordsTxt();
            string wordsNoQuotes = e.TakeOffQuotationMarks(words);

            Debug.WriteLine(words);
            Debug.WriteLine(wordsNoQuotes);
            Assert.IsNotEmpty(wordsNoQuotes);
        }

        [Test]
        public void ConvertCSVStringToList_GivenCSVString_ShouldReturnAList()
        {
            string words = e.LoadWordsTxt();
            string wordsNoQuotes = e.TakeOffQuotationMarks(words);
            List<string> listOfWords = e.ConvertCsvStringToList(wordsNoQuotes);
            Debug.WriteLine(listOfWords);
            Assert.IsNotEmpty(listOfWords);
            CollectionAssert.IsNotEmpty(listOfWords);
            CollectionAssert.AllItemsAreUnique(listOfWords);
        }

        [Test]
        public void GetFirst1000TriangeNumbers_CallMethod_ShouldReturnAListOfTriangleNumbersUnder1000()
        {
            List<int> listOfTriangeNumbers = e.GetFirst1000TriangeNumbers();
            int[] intArrayOfKnowTriangeNumbers = new int[] { 1, 3, 6, 10, 15, 21, 28, 36, 45, 55 };
            foreach (var knownTriangeNumber in intArrayOfKnowTriangeNumbers)
                CollectionAssert.Contains(listOfTriangeNumbers, knownTriangeNumber);
        }

        [Test]
        public void IsTriangleNumber_GivenA1_ShouldReturnTrueAsItIsATriangleNumber()
        {
            bool result = e.IsTriangleNumber(1);

            Assert.IsTrue(result);
        }

        [Test]
        public void IsTriangleNumber_GivenA2_ShouldReturnFalseAsItIsNotATriangleNumber()
        {
            bool result = e.IsTriangleNumber(2);

            Assert.IsFalse(result);
        }

        [Test]
        public void IsTriangleNumber_GivenA6_ShouldReturnFalseAsItIsNotATriangleNumber()
        {
            bool result = e.IsTriangleNumber(6);

            Assert.IsTrue(result);
        }

        [Test]
        public void IsTriangleNumber_Given55_ShouldReturnTrueAsItIsATriangleNumber()
        {
            bool result = e.IsTriangleNumber(55);

            Assert.IsTrue(result);
        }

        [Test]
        public void GetWordValue_GivenSKY_ShouldReturn55()
        {
            int result = e.GetWordValue("SKY");

            Assert.AreEqual(55, result);
        }

        [Test]
        public void GetWordValue_GivenSKZ_ShouldReturn56()
        {
            int result = e.GetWordValue("SKZ");

            Assert.AreEqual(56, result);
        }

        [Test]
        public void GetWordValue_GivenAAA_ShouldReturn3()
        {
            int result = e.GetWordValue("AAA");

            Assert.AreEqual(3, result);
        }

        [Test]
        public void HowManyAreTriangleWords_GivenNothing_ShouldReturnTheNumberOfWordsWhichAreTriange()
        {
            var sw = Stopwatch.StartNew();
            int result = e.HowManyAreTriangeWords();
            sw.Stop();
            Debug.WriteLine(String.Format("Answer = {0}, took {1}ms", result, sw.Elapsed.TotalMilliseconds));
            Assert.AreEqual(162, result);
        }
    }

and the code:

public class Euler42
    {
        List<int> _first1000TriangeNumbers;

        public Euler42()
        {
            _first1000TriangeNumbers = GetFirst1000TriangeNumbers();
        }

        public string LoadWordsTxt()
        {
            using (var streamReader = new StreamReader("words.txt"))
                return streamReader.ReadToEnd();
        }

        public string TakeOffQuotationMarks(string result)
        {
            return result.Replace("\"", "");
        }

        public List<string> ConvertCsvStringToList(string csvstring)
        {
            string[] stringArray = csvstring.Split(',');
            return stringArray.ToList();
        }

        public List<int> GetFirst1000TriangeNumbers()
        {
            var triangeNumberList = new List<int>();
            for (int n = 1; n < 1000; n++)
            {
                double t = 0.5 * n * (n + 1);
                triangeNumberList.Add(Convert.ToInt32(t));
            }
            return triangeNumberList;
        }

        public bool IsInteger(double number)
        {
            return (number % 1 == 0);
        }

        public bool IsTriangleNumber(int numberToTry)
        {
            //first method is precomputing the triangle numbers and comparing
            //var listOfTriangleNumbers = first1000TriangeNumbers;
            //if (listOfTriangleNumbers.Contains(i))
            //    return true;

            //second method is testing each number to see if it is triangular
            //equation is the result of solving original with
            //quadratic equation
            double squareRoot = Math.Sqrt(1 + (8*numberToTry));
            double n = (-1 + squareRoot)/2;
            return IsInteger(n);
        }

        public int GetWordValue(string inputString)
        {
            //get the word and split into each letter
            int letterCount = inputString.Length;
            int wordValue = 0;
            for (int i = 0; i < letterCount; i++)
            {
                char x = inputString[i];   

                //get the position of that letter eg a=1, b=2, c=3
                int z = Convert.ToInt32(x);
                int charPosition = z - 64;
                wordValue += charPosition;
            }
            
            return wordValue;
        }

        public int HowManyAreTriangeWords()
        {
            string result = LoadWordsTxt();
            string result2 = TakeOffQuotationMarks(result);
            List<string> result3 = ConvertCsvStringToList(result2);

            int counter = 0;
            foreach (var word in result3)
            {
                int result4 = GetWordValue(word);
                bool result5 = IsTriangleNumber(result4);
                if (result5)
                    counter++;
            }

            return counter;
        }
    }

| | # 
# Thursday, 30 December 2010
( Euler )

Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. (see project Euler!)

http://www.csharp-station.com/Tutorials/Lesson02.aspx

Type Size (in bits) Range
sbyte 8 -128 to 127
byte 8 0 to 255
short 16 -32768 to 32767
ushort 16 0 to 65535
int 32 -2147483648 to 2147483647
uint 32 0 to 4294967295
long 64 -9223372036854775808 to 9223372036854775807
ulong 64 0 to 18446744073709551615
char 16 0 to 65535

or in .NET4 System.Numerics.BigInteger.. remember to add the reference first, then put in the using statement.

My first try was using BigInteger :-)

[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
string csvStringOfNumbers = "37107287533902102798797998220837590246510135740250," +
"46376937677490009712648124896970078050417018260538," +
string[] numbers = csvStringOfNumbers.Split(',');
BigInteger number = 0;
BigInteger sum = 0;
for (int i = 0; i < 100; i++)
{
number = BigInteger.Parse(numbers[i]);
sum += number;
}

string sumAsString = sum.ToString();
string firstTen = sumAsString.Substring(0, 10);

Assert.AreEqual(1, firstTen);
}
| | # 
# Wednesday, 29 December 2010
( Euler )

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

Finding ‘Triangle numbers’ can be done by either:

[TestMethod]
public void Get6thTriangenumber()
{
int result = GetTriangleNumber(6);
Assert.AreEqual(21, result);
}

[TestMethod]
public void Get7thTriangenumber()
{
int result = GetTriangleNumber(7);
Assert.AreEqual(28, result);
}

 

public int GetTriangleNumber(int nThNumberInTriangleSequence)
{
int sumOfNumbers = 0;
for (int i = 1; i <= nThNumberInTriangleSequence; i++)
sumOfNumbers += i;

return sumOfNumbers;
}

or we could use the summation formula (faster).. this sums up n numbers in a sequence eg 1,2,3,4,5,6 (see first test above)

public int GetTriangleNumber(int nThNumberInTriangleSequence)
{
int sumOfNumbers = nThNumberInTriangleSequence * (nThNumberInTriangleSequence + 1) / 2;
return sumOfNumbers+1;
}

Factorising – What integers will it divide by with no remainder?

Let us list the factors of the first seven triangle numbers:

1: 1
3: 1,3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

http://www.mathsisfun.com/numbers/factors-all-tool.html

[TestMethod]
public void GetFactorCount36() // an exact square
{
int result = GetFactorCount(36);
Assert.AreEqual(9, result);
}

[TestMethod]
public void GetFactorCount45()
{
int result = GetFactorCount(45);
Assert.AreEqual(6, result);
}

[TestMethod]
public void GetFactorCount55()
{
int result = GetFactorCount(55);
Assert.AreEqual(4, result);
}

[TestMethod]
public void GetFactorCount30() // this isn't triangular
{
int result = GetFactorCount(30);
Assert.AreEqual(8, result);
}

Really Simple Factorisation to Get How Many Factors
public int GetFactorCount(int numberToCheck)
{
// we know 1 is a factor and the numberToCheck
int factorCount = 2;
// start from 2 as we know 1 is a factor, and less than as numberToCheck is a factor
for (int i = 2; i < numberToCheck; i++)
{
if (numberToCheck % i == 0)
factorCount++;
}
return factorCount;
}

However this isn’t fast enough.
Factorisation using Square Root

find square root of the number eg for 30 it is 5.477.  Then find all factors below that sqrt, then double.  if number is an exact square then add one.

eg 30

1*30 = 30
2*15 = 30
3*10 = 30
5*6 = 30
sqrt of 30 = 5.477
6*5 = 30
10*3 = 30
15*2 = 30
30*1 = 30

 
public int GetFactorCount(int numberToCheck)
{
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(numberToCheck));

// Start from 1 as we want our method to also work when numberToCheck is 0 or 1.
for (int i = 1; i < sqrt; i++)
{
if (numberToCheck % i == 0)
factorCount += 2; // We found a pair of factors.
}

// Check if our number is an exact square.
if (sqrt * sqrt == numberToCheck)
factorCount++;

return factorCount;
}

 

| | # 
# Monday, 27 December 2010
( Euler )

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

Here is code which didn’t work as I’d used int’s instead of longs:

[TestClass]
public class UnitTest1
{
[TestMethod]
public void CalculateTheSumOfPrimesBelow10()
{
long result = PrimeTester.calculateTheSumOfPrimesBelow(10);
Assert.AreEqual(17, result);
}

[TestMethod]
public void CalculateTheSumOfPrimesBelow20()
{
long result = PrimeTester.calculateTheSumOfPrimesBelow(20);
Assert.AreEqual(77, result);
}


[TestMethod]
public void CalculateTheSumOfPrimesBelow2million()
{
int result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
Assert.AreEqual(1179908154, result); // 1,179,908,154 .. this was what I got with an int...
// correct answer was 142,913,828,922 with a long
}
}


public static class PrimeTester
{
public static int calculateTheSumOfPrimesBelow(int maxPrimeBelow)
{
// we know 2 is a prime number
int sumOfPrimes = 2;
int currentNumberBeingTested = 3;
while (currentNumberBeingTested < maxPrimeBelow)
{
double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);

bool isPrime = true;
for (int i = 2; i <= squareRootOfNumberBeingTested; i++)
{
if (currentNumberBeingTested % i == 0)
{
isPrime = false;
break;
}
}

if (isPrime)
sumOfPrimes += currentNumberBeingTested;

currentNumberBeingTested += 2; // as we don't want to test even numbers
}
return sumOfPrimes;
}
}

and here is the working version with the checked keyword:


[TestMethod]
public void CalculateTheSumOfPrimesBelow2million()
{
long result = PrimeTester.calculateTheSumOfPrimesBelow(2000000); // 2million
Assert.AreEqual(1179908154, result); // 1,179,908,154 .. this was what I got with an int...
// correct answer was 142,913,828,922 with a long
}
}


public static class PrimeTester
{
public static long calculateTheSumOfPrimesBelow(int maxPrimeBelow)
{
// we know 2 is a prime number
int sumOfPrimes = 2;
int currentNumberBeingTested = 3;
while (currentNumberBeingTested < maxPrimeBelow)
{
double squareRootOfNumberBeingTested = (double)Math.Sqrt(currentNumberBeingTested);

bool isPrime = true;
for (int i = 2; i <= squareRootOfNumberBeingTested; i++)
{
if (currentNumberBeingTested % i == 0)
{
isPrime = false;
break;
}
}

checked
{
if (isPrime)
sumOfPrimes += currentNumberBeingTested;
}

currentNumberBeingTested += 2; // as we don't want to test even numbers
}
return sumOfPrimes;
}
}
 
or we can use a compiler option tick for check for arithmetic overflow/underflow.
screen

| | # 
( Euler )

Attacked this using TDD one step at a time:

[TestMethod]
public void GetRow1Col2ShouldBe99()
{
int result = ArrayTester.GetData(1, 2);
Assert.AreEqual(99, result);
}

[TestMethod]
public void GetHorizontalProductOfFirstFourNumbersInRow0()
{
int resultingProduct = 0;
for (int i = 0; i <= 3; i++)
{
if (i == 0)
resultingProduct = ArrayTester.GetData(0, 0);
else
resultingProduct = resultingProduct * ArrayTester.GetData(0, i);
}

Assert.AreEqual(34144, resultingProduct);
}

[TestMethod]
public void FindMaxHorizonatalProductsInRow0()
{
int result = ArrayTester.FindMaxHorizonalProductInRow(0);
Assert.AreEqual(4204200, result);
}

and code:

public static int FindMaxHorizonalProductInRow(int row)
{
List<int> listOfProducts = new List<int>();
for (int startingPosition = 0; startingPosition <= 16; startingPosition++) // as we know it will finish at 19
{
int resultingProduct = 0;
for (int j = 0; j <= 3; j++)
{
if (j == 0)
resultingProduct = ArrayTester.GetData(row, startingPosition);
else
resultingProduct = resultingProduct * ArrayTester.GetData(row, startingPosition + j);
}
listOfProducts.Add(resultingProduct);
}
return listOfProducts.Max();
}

public static int GetData(int row, int col)
{
int[,] numberArray = { { 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 },
{49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00},
{81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 },
{52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91},
{22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80},
{24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50},
{32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70},
{67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21},
{24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72},
{21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95},
{78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92},
{16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57},
{86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58},
{19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40},
{04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66},
{88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69},
{04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36},
{20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16},
{20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54},
{01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48}
};
int result = numberArray[row, col];
return result;
}

then just build out the solution using:

horizontal checking

vertical checking

diagonalDown checking

diagonalUp checking

| | # 
# Friday, 17 December 2010
( Euler )

Unit testing paying dividends now.. this was my first try, and importantly I got the answer right first time.  This is what is good about TDD.  Refactoring (which this code needs!) comes later.

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

 

[TestClass]
public class UnitTest1
{
[TestMethod]
public void maxValueOf5()
{
pythag pythag = new pythag();
List<string> listOfStrings = pythag.findAllPythagorasTripletsUnder(5);
Assert.IsNotNull(listOfStrings);
}

[TestMethod]
public void passInAStringOfNumbersAndGetBackProduct()
{
pythag pythag = new pythag();
List<string> listOfStrings = new List<string>();
listOfStrings.Add("5,4,3");
int result = pythag.doNumberCrunch(listOfStrings);
Assert.AreEqual(60, result);
}

[TestMethod]
public void mainRun()
{
pythag pythag = new pythag();
List<string> listOfStrings = pythag.findAllPythagorasTripletsUnder(600);
int result = pythag.doNumberCrunch(listOfStrings);
Assert.AreEqual(123, result); // 31875000
}

}

public class pythag
{
public List<string> findAllPythagorasTripletsUnder(int maxValueOfHypotenuse)
{
List<string> listOfString = new List<string>();
for (int c = 1; c <= maxValueOfHypotenuse; c++)
{
for (int b = 1; b <= maxValueOfHypotenuse; b++)
{
for (int a = 1; a <= maxValueOfHypotenuse; a++)
{
if (Math.Pow(a,2) == Math.Pow(b,2) + Math.Pow(c,2))
listOfString.Add(a.ToString() + "," + b.ToString() + "," + c.ToString());
}
}
}
return listOfString;
}

public int doNumberCrunch(List<string> listOfStrings)
{
int product = 0;
foreach (string item in listOfStrings)
{
string[] numbers = item.Split(',');
int a = Convert.ToInt32(numbers[0]);
int b = Convert.ToInt32(numbers[1]);
int c = Convert.ToInt32(numbers[2]);

if (a + b + c == 1000)
product = a * b * c;
}
return product;
}
}

And Phils (and I’ve made it fit into testing runner).   Goto.. but it works and is simple to read!

[TestMethod]
public void testPhilsWayByCheckingAnswerIsCorrect()
{
philsWay philsWay = new philsWay();
double result = philsWay.solveProblem();
Assert.AreEqual(31875000, result); // 31875000 is correct
}

}

public class philsWay
{
public double solveProblem()
{
double answer = 0;
for (int a = 1; a < 100000; a++)
{
for (int b = a; b < 100000; b++)
{

double c = Math.Sqrt((a * a) + (b * b));
if (a + b + c == 1000)
{
Console.WriteLine(a + "," + b + "," + c);
answer = a * b * c;
goto Foo;
}
}
}

Foo:
return answer;
}
}

and here is refactored version of my code:

public List<string> findAllPythagorasTripletsUnder(int maxValueOfHypotenuse)
{
List<string> listOfString = new List<string>();
for (int a = 1; a <= maxValueOfHypotenuse; a++)
{
for (int b = 1; b <= maxValueOfHypotenuse; b++)
{
int c = Convert.ToInt32(Math.Sqrt((a * a) + (b * b))); // converting to int to avoid getting positive double results
if (Math.Pow(c, 2) == Math.Pow(a, 2) + Math.Pow(b, 2))
listOfString.Add(a.ToString() + "," + b.ToString() + "," + c.ToString());
}
}
return listOfString;
}

| | # 
# Thursday, 16 December 2010
( Euler )

Find the largest Product.. I got product wrong initially.  I summed instead.  Unit testing was great as when I realised my mistake was an easy fix, and had confidence in the code.

 

[TestClass]
public class UnitTest1
{
[TestMethod]
public void findGreatestProductOf5ConsecutiveDigitsInSimpleString()
{
string stringOfNumbers = "1111112341111";
ProductFinder productFinder = new ProductFinder();
int result = productFinder.findGreatestProduct(stringOfNumbers);
Assert.AreEqual(11, result);

}

[TestMethod]
public void findGreatestProductOf5ConsecutiveDigitsInLongString()
{
string stringOfNumbers = "731671765313306249192251196744265747423553...";
ProductFinder productFinder = new ProductFinder();
int result = productFinder.findGreatestProduct(stringOfNumbers);
Assert.AreEqual(123, result);
}
}

public class ProductFinder
{
public int findGreatestProduct(string stringOfNumbers)
{
//try first 3
int lengthOfString = stringOfNumbers.Count();
List<int> listOfResults = new List<int>();

char[] numbers = stringOfNumbers.ToArray();
for (int i = 0; i < lengthOfString-6; i++)
{
int first = Convert.ToInt32(stringOfNumbers.Substring(i, 1));
int second = Convert.ToInt32(stringOfNumbers.Substring(i+1, 1));
int third = Convert.ToInt32(stringOfNumbers.Substring(i+2, 1));
int fourth = Convert.ToInt32(stringOfNumbers.Substring(i+3, 1));
int fifth = Convert.ToInt32(stringOfNumbers.Substring(i+4, 1));

int result = first * second * third * fourth * fifth;
listOfResults.Add(result);
}

int largestProduct = listOfResults.Max();
return largestProduct;
}
}

| | # 
( Euler )

Find the 10001th Prime

I used the test runner here to give me the answer.. didn’t even use a console application.

[TestClass]
public class UnitTest1
{
[TestMethod]
public void getSixthPrime()
{
PrimeTester primeTester = new PrimeTester();
int result = primeTester.generateThisNumberOfPrimes(6);
Assert.AreEqual(13, result);
}

[TestMethod]
public void getSeventhPrime()
{
PrimeTester primeTester = new PrimeTester();
int result = primeTester.generateThisNumberOfPrimes(7);
Assert.AreEqual(17, result);
}

[TestMethod]
public void getAnswerPrime() //10001
{
PrimeTester primeTester = new PrimeTester();
int result = primeTester.generateThisNumberOfPrimes(10001);
Assert.AreEqual(12345, result);
}

and the class:
public class PrimeTester
{
public int generateThisNumberOfPrimes(int numberOfPrimesToGenerate)
{
List<int> primes = new List<int>();

int toGenerate = 2147483630; // nearly the largest int.
primes.Add(2);

int currentNumberBeingTested = 3;
while (primes.Count < toGenerate)
{
int squareRootOfNumberBeingTested = (int)Math.Sqrt(currentNumberBeingTested);

bool isPrime = true;
for (int i = 0; i < primes.Count && (primes[i] <= squareRootOfNumberBeingTested); ++i)
{
if (currentNumberBeingTested % primes[i] == 0)
{
isPrime = false;
break;
}
}

if (isPrime)
primes.Add(currentNumberBeingTested);

if (primes.Count == numberOfPrimesToGenerate)
break;

currentNumberBeingTested += 2; // as we don't want to test even numbers
}
return primes[primes.Count-1];
}
}

| | # 
( Euler | TDD | VS2010 )

I decided to try and do Test Driven Development here, so avoid any small problems.

Problem was that my test harness in VS2010 wouldn’t start the agent: http://stackoverflow.com/questions/4446416/vs2010-test-runner-unable-to-start-agent-process (Edit: It was Avira AntiVirus that was the culprit)

alt text

After reinstalling VS2010, and trying to remember all the changes I’ve made since it last worked.. I can run all the tests, just not in the debugger.  Which is very useful.

Euler problem is interesting:

The sum of the squares of the first ten natural numbers is,

12 + 22 + ... + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + ... + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

Source code here:    

 

class Program
{
static void Main(string[] args)
{
stuff thing = new stuff();
double sumOfSqaures = thing.sumOfSquares(100);
double sqaureOfSums = thing.SquareOfSum(100);
double result = sqaureOfSums - sumOfSqaures;
Console.WriteLine(result);
}
}

public class stuff
{
public double sumOfSquares(double upToInt)
{
double total = 0;
for (int i = 1; i <= upToInt; i++)
total += Math.Pow(i, 2);

return total;
}

public double SquareOfSum(int upToInt)
{
double sum = 0;
for (int i = 0; i <= upToInt; i++)
sum += i;

return Math.Pow(sum, 2);
}
}

and test code:

[TestClass]
public class UnitTest1
{
[TestMethod]
public void SumOfSquaresOfFirst10()
{
stuff thing = new stuff();
double result = thing.sumOfSquares(10);
Assert.AreEqual(385, result);
}

[TestMethod]
public void SquareOfSumOfFirst10()
{
stuff thing = new stuff();
double result = thing.SquareOfSum(10);
Assert.AreEqual(3025, result);
}

[TestMethod]
public void DifferenceBetweenTwoAbove()
{
stuff thing = new stuff();
double sumOfSqaures = thing.sumOfSquares(10);
double sqaureOfSums = thing.SquareOfSum(10);
double result = sqaureOfSums - sumOfSqaures;
Assert.AreEqual(2640, result);
}

}

It was great using TDD.. made it very easy, and got answer right first time!

| | # 
# Monday, 13 December 2010
( Euler )

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Or ‘Exactly Divisible’

int numberToTest = 1;
while (1 == 1)
{
bool divisible = true;
for (int j = 1; j <= 20; j++)
{
if (numberToTest % j != 0)
{
divisible = false;
break;
}
}
if (divisible)
break;
numberToTest++;
}

for (int i = 1; i <= 20; i++)
Console.WriteLine(i + " " + numberToTest / i);

Console.WriteLine(numberToTest); // 232 792 560

This took me a while with an elementary programming mistake.. corrected and got it.  I will try and build in more testing into the following problems to avoid simple errors.
| | # 
# Sunday, 12 December 2010
( Euler )

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.

Find the largest palindrome made from the product of two 3-digit numbers.

static void Main(string[] args)
{
IList<int> listOfPalindromes = new List<int>();
for (int i = 100; i <= 999; i++)
{
for (int j = 100; j <= 999; j++)
{
int product = i * j;
if (product >= 100000)
{
string productAsString = Convert.ToString(product);
if ((productAsString[0] == productAsString[5]) && (productAsString[1] == productAsString[4]) && (productAsString[2] == productAsString[3]))
listOfPalindromes.Add(product);
}
}
}

foreach (var number in listOfPalindromes.OrderBy(x => x))
Console.WriteLine(number.ToString());
}

906609

Phils way:

static void Main(string[] args)
{
int max = 0;

for (int a = 999; a > 2; a--)
{
for (int b = 999; b > 2; b--)
{

string ans = Convert.ToString(a * b);
int counter = 0;
for (int x = 0; x < ans.Length; x++)
{
if (ans[x] == ans[ans.Length - x-1])
{
counter++;
}
}

if (counter == ans.Length && Convert.ToInt32(ans)>max)
{
max = Convert.ToInt32(ans);

}
}
}

Console.WriteLine(max);
Console.ReadLine();

| | # 
( Euler )

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

The secret here is that you only need to test prime numbers up to the square root of 600billion number above.

Why?

     
18 * 2 36
17    
16    
15    
14    
13    
12 * 3 36
11    
10    
9 * 4 36
8    
7    
6 * 6 36
5   36
4 * 9 36
3 * 12 36
2 * 18 36

Go above 6, and 9 * 4 is the same as 4 * 9… same for 12 * 3, 18 * 2.

So we need only find all the primes up to (int)Math.Sqrt(numberToGetLargestPrimeFactorOf); // 775146

Then see which is the largest which divides by the 600billion number

which is: 6857  (divides it as: 87,625,999)

There are no larger primes which are divisible by the 600 billion number.

// What is the largest prime factor of the number 600851475143 ? 600,851,475,143
// we only need to check prime numbers up to Sqrt(600851475143)
static void Main(string[] args)
{
long numberToGetLargestPrimeFactorOf = 600851475143;
int squareRootOfnumberToGetLargestPrimeFactorOf = (int)Math.Sqrt(numberToGetLargestPrimeFactorOf); // 775146

List<int> listOfPrimes = generatePrimes(775146);
List<int> listOfPrimeFactors = new List<int>();
for (int i = listOfPrimes.Count-1; i > 0; i--)
{
int intToDivideBy = listOfPrimes[i];
if (numberToGetLargestPrimeFactorOf % intToDivideBy == 0)
{
listOfPrimeFactors.Add(intToDivideBy);
Console.WriteLine("factor is " + intToDivideBy.ToString());
}
}
}

public static List<int> generatePrimes(int toGenerate)
{
List<int> primes = new List<int>();

if (toGenerate > 0) primes.Add(2);

int curTest = 3;
while (primes.Count < toGenerate)
{
int sqrt = (int)Math.Sqrt(curTest);

bool isPrime = true;
for (int i = 0; i < primes.Count && (primes[i] <= sqrt); ++i)
{
if (curTest % primes[i] == 0)
{
isPrime = false;
break;
}
}

if (isPrime)
primes.Add(curTest);
curTest += 2;
}
return primes;
}

Some other code which was much less efficient, but more readable in my opinion was:

IEnumerable<int> listOfInts = Enumerable.Range(2, 775146).Where(i => (i % 2 != 0));
IList<int> listOfPrimes = new List<int>();

foreach (int intToCheck in listOfInts)
{
bool isPrime = true;
// divide the intToCheck against all numbers in the list lower than it
foreach (int intToDivideBy in listOfInts)
{
if (intToCheck != intToDivideBy)
{
if ((intToCheck % intToDivideBy) == 0)
isPrime = false;
}
}
if (isPrime)
listOfPrimes.Add(intToCheck);
}

foreach (int intToDivideBy in listOfPrimes.Reverse())
{
if (numberToGetLargestPrimeFactorOf % intToDivideBy == 0)
{
listOfPrimeFactors.Add(intToDivideBy);
break; // stop processing as found the highest
}
}

| | # 
# Wednesday, 08 December 2010
( Euler )
//Find the sum of all the even-valued terms in the sequence which do not exceed four million.
static void Main(string[] args)
{
List<int> fibList = new List<int>();
fibList.Add(1); // index 0
fibList.Add(2); // index 1

int i = 2;
while (fibList[fibList.Count-1] < 4000000)
{
int secondLastValue = fibList[i - 2];
int lastValue = fibList[i - 1];
int valueToAdd = secondLastValue + lastValue;
fibList.Add(valueToAdd);
i++;
}

fibList.RemoveAt(fibList.Count - 1); // remove last item in list as it will be over the 4,000,000 limit

// get even values
List<int> fibListEven = new List<int>();
foreach (int intToTry in fibList)
{
if (intToTry % 2 == 0)
fibListEven.Add(intToTry);
}

int sumOfEvens = 0;
foreach (int intToDisplay in fibListEven)
sumOfEvens += intToDisplay;

Console.WriteLine(sumOfEvens.ToString());
Console.ReadLine(); // should be 4613732
}

Found this on http://stackoverflow.com/questions/1580985/finding-fibonacci-sequence-in-c-project-euler-exercise
 
[TestMethod]
public void TestMethod1()
{
long result = 0;

foreach (int i in Fibonacci().TakeWhile(i => i < 4000000).Where(j => j % 2 == 0))
result += i;

Assert.AreEqual(1, result); // 4,613,732
}

public IEnumerable<int> Fibonacci()
{
int n1 = 0;
int n2 = 1;

yield return 1;
while (true)
{
int n = n1 + n2;
n1 = n2;
n2 = n;
yield return n;
}
}

| | # 
( c# language | Euler | Linq )

This is a fun site:

http://projecteuler.net

The first problem is:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

static void Main(string[] args)
{
int overallSum = 0;
for (int i = 1; i < 1000; i++)
{
if ((i % 3 == 0) || (i % 5 == 0))
overallSum += i;
}
Console.WriteLine("overall sum is: " + overallSum.ToString());
Console.ReadLine();
}
// should be 233168

or Phils way:

//Find the sum of all the multiples of 3 or 5 below 1000.
//There is a summation formula which states
//The sum of all numbers from i = 1 to i = n is n(n+1)/2
static void Main(string[] args)
{
int total = (3 * Convert.ToInt32(999 / 3) * (Convert.ToInt32((999 / 3)) + 1)) / 2
+ (5 * Convert.ToInt32(999 / 5) * (Convert.ToInt32((999 / 5)) + 1)) / 2
- (15 * Convert.ToInt32(999 / 15) * (Convert.ToInt32((999 / 15)) + 1)) / 2;

Console.WriteLine("overall sum is: " + total.ToString());
Console.ReadLine();

}

from http://answers.yahoo.com/question/index?qid=20100422031504AAfmpJ5)

or Simons way using method syntax (or fluent)

int result = Enumerable.Range(0, 1000)  // generates a sequence of numbers in a range
.Where(i => i % 3 == 0 || i % 5 == 0) // filter using lambda expression
.Sum(); // sum of int32 using extension methods


and for fun, using method and query syntax
 
// get the ones divisible by 3 in the list - Method syntax
IEnumerable<int> listOfDivisibleBy3Method = listOfInts
.Where(i => i % 3 == 0);

// get the ones divisible by 3 in the list - Query syntax
IEnumerable<int> listOfDivisibleBy3Query = from number in listOfInts
where (number % 3 == 0)
select number;

http://stackoverflow.com/questions/214500/which-linq-syntax-do-you-prefer-fluent-or-query-expression

| | #