Project Euler Problem 6 and 7 in F#

Project Euler problem 6 is one of the easiest that I have encountered so far. Also, Problem 7 is quite easy to solve once you have a function for prime numbers (something we did in Problem 3). Therefore, in this post I give 2 problems for the price of 1! :)

Problem 6

Let’s have a look at the question for Problem 6:

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

1² + 2² + … + 10² = 385
The square of the sum of the first ten natural numbers is,

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

There are a few tricks to calculate the sum of the squares (see for example here). However, given the limited size of the problem at hand, brute-force is perfectly fine: it shows once more the elegance of a declarative solution.

#light
open System

let square x = x * x

// a² + b²  + ... + z² 
let sum_of_square max =
    Seq.unfold (fun x -> if x > max then None else Some(x*x, x+1)) 1
    |> Seq.sum

// (a +b + ... + z)² 
let square_of_sum max =
    {1 .. max}
    |> Seq.sum
    |> square

let problem_6 max =
    square_of_sum(max) - sum_of_square(max)

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?

As I mentioned in the introduction, this one is fairly easy once you know how to tell whether a given number is prime or not. We did that exercise in Problem 3.

There’s a catch though: this time we are counting the prime numbers. In the test we did in Problem 3 there was a small error that in that context was irrelevant: the test returned true also for 0 and 1, which strictly speaking are not prime numbers (2 is considered to be the first prime number).

For this reason, I have modified the code of is_prime a bit so that the first prime will be 2, the second 3, and so on as appropriate.

#light
open System

let is_prime x =
    let rec check i =
        x > 1L && 
       (double i > sqrt (double x) || (x % i <> 0L && check (i + 1L)))
    check 2L                 

let sequence_of_first_n_primes n =
    Seq.initInfinite (fun x -> int64 x)
    |> Seq.filter is_prime
    |> Seq.take n
    |> Seq.max

Ok… break time is over. Problem 8 looks a bit more challenging. See you when I have got a nice solution for that.

See all Project Euler problems solutions.

kick it on DotNetKicks.com

Shout it

This entry was posted in .NET, F# and tagged , , . Bookmark the permalink.