Monday, 14 November 2011

C# vs C++ syntax, round 1

While I was trying to learn F#, I logged on my project euler account to start with simple algorithms to practice. But when I looked the first problem, which I've solved a couple of years ago in C++, I couldn't help myself stopping putting my hands on the code editor and solving it in C# using Linq

The description of 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.


The solution in C++ is something like

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

return sum;
}

... and the equivalent in C#


public static int Prob01()
{
  return 
    Enumerable.Range(1, 999).Where(x => (x % 3) == 0 || (x % 5) == 0).Sum();
}

For me it's clear which one is more concise and better express what I'm doing.

Before I forget it, the equivalent in F# can be implemented like that:

let result = List.sum(List.filter(fun x -> x%3=0 || x%5 =0)[1..999])



No comments:

Post a Comment