Tag Archives: Project Euler

Project Euler: Problem 1 (in F#)

I have already done Project Euler Problem 1 in C#. Since I am currently learning F#, I thought I’d give it another shot:

let rec sumMultiples(data) =
    match data with
    | [] -> 0
    | head::tail when (head % 3 = 0 || head % 5 = 0) -> head + sumMultiples(tail)
    | _::tail -> sumMultiples(tail)

It produces the correct result, but seeing as how LINQ considerably simplified the C# version, and since I am a complete F# and functional programming n00b, I suspected there must be a better way.

I hate it when I’m right.

This solution is better, in my opinion:

List.sum(List.filter (fun n -> n % 3 = 0 || n % 5 = 0) [1..999]);;

Anyhow, I know I have a lot left to learn, so I’m looking forward to exploring the functional side of programming in the coming months.

Update 2010-01-08: Ooh, better yet:

[1..999] |> List.filter (fun n -> n % 3 = 0 || n % 5 = 0) |> List.sum;;

Pipelining FTW!

Project Euler: Problem 1

I just put my son down for a nap, so since I had a little spare time, I thought I’d try my hand at Project Euler.

Problem 1 was very simple. Right off the bat, I knew how I wanted to solve it:

int sum = 0;
for (int ix = 0; ix < 1000; ix++)
{
	if (ix % 3 == 0 || ix % 5 == 0)
	{
		sum += ix;
	}
}

However, I’ve been reading Jon Skeet’s excellent book, C# in Depth, so I wanted to see if I could solve it using LINQ:

int sum = Enumerable.Range(0, 1000)
	.Where(x => (x % 3 == 0 || x % 5 == 0))
	.Sum();

It still looks weird to me, but it works, so who am I to complain? :)