Project Euler 010 – F#

4 04 2011

Problem 10

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

Find the sum of all the primes below two million.

Solution

(*

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

 

Find the sum of all the primes below two million.

*)

 

open System

 

let start = DateTime.Now

 

let isPrime n =

    let m = bigint (sqrt (float n))

    [2I..m] |> List.exists (fun elem-> n % elem = 0I) |> not

 

let primeList n =

    [2I..n]

    |> List.filter isPrime

 

 

let primes  = primeList (bigint (sqrt 2000000.0))

 

let isPrimeFromList n primes =

    primes |> List.exists (fun elem-> n % elem = 0I) |> not

 

let remainingPrimes = [bigint(sqrt(2000000.0)) .. 2000000I] |> List.filter(fun elem -> isPrimeFromList elem primes)

 

printfn "%A" ((primes |> List.sum) + (remainingPrimes |> List.sum))

 

let elapsed = DateTime.Now – start

printfn "%A" elapsed

 

Discussion

I ran into some difficult with this problem as my previous prime determination algorithms were recursive and ended up overflowing the stack.  This solution takes just under 20 seconds on my laptop.  I broke the prime determination into two sections. 

The first is a really naïve solution that checks all of the numbers up to square root of 2 million.  This will give me all of the primes I need to test for primality on the remaining primes.

The second is then a prime test that uses the list of primes to determine the primality.  It’s not real fast, but it gets the job done.

Please, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).





Project Euler 009 – F#

28 03 2011

Problem 9

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.

Solution

(*

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.

 

*)

 

let testints = [1..998]

let answer = [for a in testints do

                for b in testints do

                    if b >= a

                       && a + b < 1000

                       && a*a + b*b = (1000-a-b)*(1000-a-b) then

                        yield a * b * (1000-a-b)]

             |> List.head

            

 

 

printfn "%A" answer

 

Discussion

I adapted this solution from my C# solution.  It’s actually not as clean as my C# solution which betrays its imperative origins.  I’m not sure I could come up with a much worse way to accomplish this task and yet it still runs quite snappy.  This is going to be roughly 1,000,000 iterations.  The b >= a makes several iterations pretty snappy.  Still, changing the b loop to

for b in [a..998] do

will would be a better decision.  While we’re at it, we could change testints too.  Perhaps tomorrow will have some additional discussion on optimizations.

 

If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).





Project Euler 008 – F#

21 03 2011

Problem 8

Find the greatest product of five consecutive digits in the 1000-digit number.

73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450

Solution

(*

Find the greatest product of five consecutive digits in the 1000-digit number.

*)

 

(* needed for Int32.Parse *)

open System

 

(* need to remove the line breaks *)

let digits = "73167176531330624919225119674426574742355349194934

96983520312774506326239578318016984801869478851843

85861560789112949495459501737958331952853208805511

12540698747158523863050715693290963295227443043557

66896648950445244523161731856403098711121722383113

62229893423380308135336276614282806444486645238749

30358907296290491560440772390713810515859307960866

70172427121883998797908792274921901699720888093776

65727333001053367881220235421809751254540594752243

52584907711670556013604839586446706324415722155397

53697817977846174064955149290862569321978468622482

83972241375657056057490261407972968652414535100474

82166370484403199890008895243450658541227588666881

16427171479924442928230863465674813919123162824586

17866458359124566529476545682848912883142607690042

24219022671055626321111109370544217506941658960408

07198403850962455444362981230987879927244284909188

84580156166097919133875499200524063689912560717606

05886116467109405077541002256983155200055935729725

71636269561882670428252483600823257530420752963450".Replace("\r\n","")

 

let products (str:string) =

    let indices = [0..str.Length-5]

    [for i in indices do

        yield Int32.Parse(str.Chars(i).ToString())

            * Int32.Parse(str.Chars(i+1).ToString())

            * Int32.Parse(str.Chars(i+2).ToString())

            * Int32.Parse(str.Chars(i+3).ToString())

            * Int32.Parse(str.Chars(i+4).ToString())]

 

let answer = products digits

             |> List.max

 

printfn "%A" (answer)

 

Discussion

This problem is almost trivial.  I’m not sure there is more to say on it. 

If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).





Project Euler 007 – F#

14 03 2011

Problem 7

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10001st prime number?

Solution

(*

 By listing the first six prime numbers:

 2, 3, 5, 7, 11, and 13, we can see that

 the 6th prime is 13.

 

 What is the 10001st prime number?

*)

 

let primes =

  let rec prim n (sofar: list<int>) =

      seq { if (sofar |> List.forall (fun i -> n%i <> 0)) then

                yield n

                yield! prim (n+1) (n :: sofar)

            else

                yield! prim (n+1) sofar }

  prim 2 []

 

let tenthousandfirst = primes

                       |> Seq.take 10001

                       |> Seq.max

 

printfn "%A" tenthousandfirst

 

Discussion

The primes function was posted on a forum by Don Syme.  The use of the infinite sequence is just awesome – again.  20+ years of imperative programming has taken it’s toll so it’s going to take a lot more effort on my part to wrap my mind around this functional stuff.  I’ll keep plugging away.

If you have any questions, leave a comment, find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).





Project Euler 006 – F#

7 03 2011

Problem 6

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.

Solution

(*

 The sum of the squares of

 the first ten natural numbers is,

 

 1^2 + 2^2 + … + 10^2 = 385

 The square of the sum of the

 first ten natural numbers is,

 

 (1 + 2 + … + 10)^2 = 55^2 = 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.

*)

 

let sqr x = x*x

let numbers = [1..100]

 

let sumofsqrs x = x

                  |> List.map sqr

                  |> List.sum

 

let sqrofsum x = x

                 |> List.sum

                 |> sqr

 

let answer x = sqrofsum x – sumofsqrs x

 

printfn "%A" (answer numbers)

Discussion

The F# solution is rather elegant once again.  There is a common math ‘trick’, but for only 100 elements there is no reason to shy away from the brute force solution.  Later this week we’ll see the trick.

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).





Project Euler 005 – F#

28 02 2011

Problem 5

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?

Solution

(*

 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?

 

*)

 

(* I have put this list in the format of

   2^4, 3^2, 5^1 …

*)

let factorsWeCareAboutLessThan20 = [pown 2 4;pown 3 2;5;7;11;13;17;19]

 

(* multiply them all together *)

let answer = factorsWeCareAboutLessThan20

             |> List.fold(fun elem acc -> elem * acc)  1

 

printfn "%A" answer

 

Discussion

This is a pretty simple problem if you know what you’re looking for.  We want to find the least common multiple of (1,2,3..20). 

The key observation here is that anything that is divisible by 16 (24) is also divisible by 2, 4 (22), and 8 (23).  Restating this as a question: What is the highest power of 2 we need to concern ourselves with?  25 = 32  which is too big (bigger than 20).  24 = 16 so that’s just right.  Rinse and repeat with other primes.

Later this week we might look at a more automated approach… if you’re lucky.

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).





Project Euler 004 – F#

21 02 2011

This has content has been moved. Please find it here:

http://eulersolutions.com/2011/05/19/project-euler-004-f/





Project Euler 003 – F#

14 02 2011

This has content has been moved. Please find it here:

http://eulersolutions.com/2011/05/18/project-euler-003-f/





Project Euler 002 – F#

7 02 2011

This has content has been moved. Please find it here:

http://eulersolutions.com/2011/05/17/project-euler-002-f/





Project Euler 001 – F#

1 02 2011

This has content has been moved.  Please find it here:

http://eulersolutions.com/2011/05/16/project-euler-001f/