Update 6: When you think you’re done, think twice. The code should be valid even when the range contains some negative value
var primes =
Enumerable.Range(-10, 34).Aggregate<int , IEnumerable<int>>(new int[] {},
(list, x) =>
x >1 && list.All(y => x%y != 0)
? list.Union(new[] {x})
: list);
End update
Update 5: Long story short, Linq is not the type of thing you’d use when finding primes.
Update 4: Removing “if” in expense of reduced speed
Enumerable.Range(1, 34).Aggregate<int , IEnumerable><int>>(new int[] {},
(list, x) =>
x != 1 && list.All(y => x%y != 0)
? list.Union(new[] {x})
: list);
End update
Update 3: Making the code a bit faster by dividing only primes found so far
var primes =
Enumerable.Range(1, 34).Aggregate(new List<int>(), (list, x) =>
{
if(x!=1&&list.All(y=>x%y!=0))
{
list.Add(x);
}
return list;
});
End update
Update 2: Using all, one can have one step cleaner code.
var primes =
Enumerable.Range(1, 34).Where(x =>
x == 2 || (x != 1 &&
Enumerable.Range(2, (int) (Math.Sqrt(x)))
.All(y=>x%y!=0)));
End update
Update: Using any, one can make a bit faster implementation of it
var primes =
Enumerable.Range(1, 34).Where(x =>
x == 2 || (x != 1 &&
!Enumerable.Range(2, (int) (Math.Sqrt(x)))
.Any(y=>x%y==0)));
End update
Here is my solution to TekPub’s Mastering Linq Challenge appeared on Justin Etheredge’s blog
var primes =
Enumerable.Range(1, 34).Where(x =>
x == 2 || (x != 1 &&
Enumerable.Range(2, (int) (Math.Sqrt(x)))
.Where(y => (x%y) == 0).Count() == 0));
Not very efficient, but simple :)
734eca6b-2bc9-4145-bdde-94a696a42010|0|.0