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.