TekPub's Mastering LINQ Challenge

My friend and colleague Justin Etheredge posted a LINQ challenge to promote his new TekPub series on mastering LINQ. Justin is wicked smart and a fantastic teacher; it promises to be a good series.

The challenge is to produce “a single LINQ query which starts with Enumerable.Range(1,n) and produces a list of prime numbers from the range.” In other words:

var primes = Enumerable.Range(1, SomePositiveValue).SomeLinqMethod(

Of course, being a seasoned lazy developer, my instinct was to search for a prime number algorithm in another language, ideally a functional language, and port it to C#. I found algorithms similar to Nenad Markovic’s clever solution to this challenge:

public IEnumerable<int> ExpectedGetPrimes(int max)
{
  return Enumerable.Range(1, max).Where(n => Enumerable.Range(1, n).Where(m => (n / m) * m == n).Count() == 2);
}

It’s clean, and I’m using it to verify my algorithm below. I like the algorithm, because it’s the definition prime number translated into code: exactly two natural number divisors: 1 and itself. It was obvious the algorithm was counting the factors, but it actually took me a minute to really grok that n and m are integers. Thus division remainders are truncated, e.g., (5/2)*2 equals 4 not 5.

Yes, I can be dense at times, and to be honest, it would have taken me a while to write that algorithm. That is just not how my brain works. When I need high performance algorithms, I turn to Google or a more mathematically minded colleague.

In the spirit of the challenge, I decided to to solve this problem in a novel way, i.e., a solution not copied from something else. So this is what I came up with:

public IEnumerable<int> MyGetPrimes(int max)
{
    return Enumerable.Range(1, max).Skip(1).Reverse()
        .Aggregate(new List<int>(), (result, value) =>
           {
               result.RemoveAll(n => n % value == 0);
               result.Add(value);
               return result;
           });
}

It’s not pretty, but it works. I’m just reversing the sequence and creating a new list. As I add each number, I’m removing any existing elements for which the current number is a factor. It’s slow, and I would never use it in production code. And to get the output in the right order (not a criterion for the challenge), you have to reverse it again. However, it does pass the tests, and technically it could be written on one line, if you have a 30" screen.

Comments

January 4. 2010 13:33

Justin Etheredge

I think this is the most creative solution for this that I have seen! Excellent work!

Justin Etheredge

May 17. 2010 01:21

pingback

Pingback from 7.mfbattle.com

Replacement 1965 Dodge Coronet Plastic Window, 1966 Dodge Coronet History

7.mfbattle.com

June 1. 2010 07:10

no credit check personal loans

Small opportunities are often the beginning of great enterprises

no credit check personal loans

June 3. 2010 16:56

Cloud Conlsulting

Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.

Cloud Conlsulting

June 3. 2010 17:41

Link building India

I must say that overall I am really impressed with this blog.It is easy to see that you are impassioned about your writing. I wish I had got your ability to write. I look forward to more updates and will be returning.

Link building India

June 4. 2010 20:41

IT consultants los angeles

I also tried the same series but my friend who is an IT consultant in Los Angeles told me that reversing the sequence and creating a new list is a really slow process and a bad idea for production code.

IT consultants los angeles

June 6. 2010 00:21

Software Development India

You are so right, algorithms can be tricky, once I needed a high performance algorithm and I took help from Software development India, they provided a very efficient service.

Software Development India

June 12. 2010 16:03

Svitlana.Net.Ua

I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now.

Svitlana.Net.Ua

June 15. 2010 16:04

няня

I would like to thank you for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. In fact your creative writing abilities has inspired me to start my own BlogEngine blog now.
http://svitlana.net.ua/staff/category/3/ гувернантка, http://svitlana.net.ua/staff/category/5/ повар, http://svitlana.net.ua/staff/category/6/ садовник, http://svitlana.net.ua/staff/category/10/ репетитор, http://svitlana.net.ua/staff/category/4 домработница, http://svitlana.net.ua/staff/category/8/ семейная пара, http://svitlana.net.ua/pages/2/ работа няней.

няня

June 21. 2010 05:23

Проститутки по вызову

Не маловажным есть то, что проститутки Сочи освоили начальные азы стриптиза и применяют его по запросам клиентов. А, клиенты часто заказывают себе танец, который помогает расслабиться и настроиться на секс. А то, что девочки, которые работают в Сочи, поднесут вам это по высшему разряду, можете даже не сомневаться.

Проститутки по вызову

June 24. 2010 16:06

e-pokeronline

You got numerous positive points there. I made a search on the issue and found nearly all peoples will agree with your blog.

e-pokeronline

June 29. 2010 03:06

Audio Visuals

Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts  into the stuff you post!! Thumbs up

Audio Visuals

June 29. 2010 03:06

Electronic Cigarettes

So far, I managed to go though only some of the posts you have here, but I find them very interesting and informative. Just want say thank you for the information you have shared.

Electronic Cigarettes

June 29. 2010 03:08

Discount Canon Printer Ink

Nice article, I am a big time fan of your site, keep up the nice work, and I will be a frequent visitor for a very long time.

Discount Canon Printer Ink

July 2. 2010 21:44

Магазин сантехники

I really got a kick out of your article. I don\\\'t really have much to say in reply, I only wanted to comment to reply with wonderful operate. good luck in 2010.

Магазин сантехники

July 6. 2010 09:54

Московские проститутки

Can you please provide more information on this subject? BTW your blog is great. Cheers.

Московские проститутки

July 9. 2010 08:07

Проститутки

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

Проститутки

July 10. 2010 09:45

Новинки сантехники

I like your blog so much that I feel I have to wish you. Happy New Year in advance. Have a nice and prosperous year ahead

Новинки сантехники

July 11. 2010 10:54

online payday loans

The world leaders in innovation and creativity will also be world leaders in everything else. http://www.clicknpayday.com

online payday loans

July 12. 2010 08:01

Web Design Company

Amazing!I also wish him good luck to defend his gold medal.I like to share it with all my friends and hope they will also encourage him.

Web Design Company

July 12. 2010 08:11

Hawaii Web Design

Thanks for this article. It's just what I was searching for. I am always interested in this subject. Will bookmark!

Hawaii Web Design

July 12. 2010 08:27

Web Design Company

Glad to visit your blog. Thanks for great post that you share to us...

Web Design Company

July 15. 2010 11:13

SEO Company California

It’s really a great post..I would like to appreciate your work and I am going to recommend it to my friends.

SEO Company California

July 29. 2010 14:49

Miami Web Designer

Thanks for sharing this information. Keep up the good work.

Miami Web Designer

Add comment




biuquote
  • Comment
  • Preview
Loading