SmoothFriction.nl

posts - 39, comments - 20, trackbacks - 0

TekPub's Mastering LINQ Challenge

I’m always up for a challenge. I still have to watch the Mastering LINQ videos up on TekPub (which is amazing by the way, I encourage you to check it out!), but someone (hi Tuna!) tweeted about a small challenge related to the series.

Basically, the challenge is to use a chained LINQ statement to create a prime number filter, without using any custom functions. Without further delay, here’s my solution:

var primes = Enumerable.Range(1, 30)
    .Where(x => x > 1)
    .Where(x => x%2 != 0 && x != 2)
    .Where(x =>
            !Enumerable.Range(2, (int) Math.Sqrt(x)).Any(y => x%y == 0)
          );

This isn’t an optimal solution, but good enough for a first version. Basically, this is what’s happening:

  • All primes are greater than one. So filter on that first.
  • All primes are odd, except the number 2. Filter on that using modulus, and a hardcoded check for 2.
  • Now comes the real work: A prime can be found by trying to divide the subject by all numbers up to the square root of the subject. If any of the divisions has no remainder, the subject is not a prime.

I’m curious to see who’ll come up with a neat solution first, as this is obviously more or less brute force. While waiting, I’ll try to come up with another solution.

Print | posted on Saturday, January 09, 2010 12:07 AM | Filed Under [ c# LINQ ]

Feedback

Gravatar

# re: TekPub's Mastering LINQ Challenge

Nice work!
1/9/2010 12:48 AM | Justin Etheredge
Gravatar

# re: TekPub's Mastering LINQ Challenge

Thanks! It's not very optimal, but I don't think I'd juse LINQ for this purpose anyway. I'm curious on where you're going to take the series though, as I've only seen the first few minutes so far.

I was going to attempt some kind of sieve method, but I couldn't quite work out how to put it in one chained linq statement without it becoming a true monstrosity. Are you going to post some original approaches on your blog? Love to see what others come up with other than this obvious one ;)
1/9/2010 12:52 AM | Erik van Brakel
Gravatar

# re: TekPub's Mastering LINQ Challenge

I dont understand why you are not including the number 2 as it is a prime number. In other words shouldn't

.Where(x => x%2 != 0 && x != 2)

Be

.Where(x => x%2 != 0 || x == 2)

Maybe I'm misunderstanding something (as usual)
2/7/2010 4:41 PM | Chris Owen

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 3 and 1 and type the answer here: