TekPub's Mastering LINQ Challenge

Just saw a good little LINQ quiz on Justin Etheredge's blog - I saw it way too late to get the TekPub subscription, but thought it looked fun anyhow. Here's my solution:

   static void Main(string[] args)
   {
     int max = 100;

     var primes = Enumerable.Range(1, max)
      .Where(i => i > 1)
      .Aggregate(Enumerable.Range(2, max - 1).ToArray(), (sieve, i) =>
      {
        if ((i > Math.Sqrt(max)) || (sieve[i - 2] == 0)) return sieve;
        for (int m = 2; m <= max / i; m++)
          sieve[i * m - 2] = 0;
        return sieve;
      })
      .Where(n => n != 0)
      ;

     foreach (var p in primes)
     {
       Console.WriteLine(p);
     }

   }

Arguably it's not pure LINQ; there's more going on inside the aggregate lambda than I'd like, but it does the job and for those into this sort of thing you should recognise it as an implementation of the Sieve of Eratosthenes.

Comments

# The TekPub LINQ Challenge And The Sieve Of Eratosthenes
Gravatar The TekPub LINQ Challenge And The Sieve Of Eratosthenes
Left by CodeThinked on 1/12/2010 6:39 PM

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 3 and 5 and type the answer here:

Preview Your Comment.