lundi 4 février 2013

C#.NET throught Euler#10

Intro

After I was finished writing my last post, I went on looking for Euler's  problem implementation in C# and I was amazed at most of the answer I found. Every question regarding Euler's implementation in C# were overtaken by people asking to get the fastest possible implementation. Even thought I am always up for speed, I think there are missing the point. C# is an incredibly powerful language if it is fighting in its own turf, but if you are looking at micro-optimization how fast can C# dereference an array element that you are outside it's comfort zone.

Problem 10

I wasn't planning on doing another post right after problem #9 but I couldn't resist seeing how well it suited the language.

So problem #10 definitions is as follows :
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
the sum of all the primes below two million.

It's simple and straight to the point.

Generating Prime

The only part that isn't totally straight forward is how I generate my prime numbers. I am using the fact that a number is prime if it is not dividable by any prime from 2, to the square root of the number. Using this explanation, you should understand my logic.

Speed

Speed was not the goal here, I did absolutely no optimisation. My only constraint was that it must end before 10 sec as Euler's rules stipulates.

Implementation

As in the last post, I will provide a brief description of new operators.
  • Any - Return true if the predicates is true for any element.
  • Sum - Sums all the element.

Final words

Is it not splendid?

It feels like you're teaching your computer to speak English. Let me defines those as prime numbers and than take all primes under 2M and sum them.

Now we are in C#'s turf. Knowing you could do this in C# it pains me to see implementation like this : http://ideone.com/55j4F

I know it is faster, I know it is more efficient, but you have lost all that makes this a great language to work with.

Aucun commentaire:

Enregistrer un commentaire