About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Friday, July 31, 2009

Project Euler Problem 1 (C# vs F#)

The problem:

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.


C#

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

namespace Euler

{

class Program

{

//Add all the natural numbers below one thousand that are multiples of 3 or 5.

//0.001 seconds

static void Main(string[] args)

{

Stopwatch sw = new Stopwatch();

sw.Start();

int total = 0;

for (int i = 1; i <>

{

if (i % 3 == 0 || i % 5 == 0)

{

total += i;

}

}

Console.WriteLine("Answer: " + total);

sw.Stop();

Console.WriteLine(sw.Elapsed);

Console.WriteLine(sw.ElapsedTicks);

Console.ReadLine();

}

}

}


The F# solution:

F#

#light

//0096404 milliseconds

open System.Diagnostics

let stopWatch = new Stopwatch()

stopWatch.Start()

printfn "%A" (List.sum(List.filter (fun n-> (n % 3) = 0 or (n % 5) = 0) [1 .. 999]))

stopWatch.Stop();

printfn "%A"stopWatch.Elapsed

printfn "%A"stopWatch.ElapsedTicks

open System

Console.ReadKey(true)




C# does it in

0.001 seconds

3606 ticks


F# does it in

0.0096404 seconds

24380 ticks


There is probably some more efficient way of doing the F#, this was however my first attempt at learning the language. Will have to see how it can do the more tougher problems.


1 comment:

Anonymous said...

for faster performance, don't take the entire list of integers from [1..999], and filter it

instead use a sequence generator for only the values which you require, and sum the sequence

-whizbang