Linq is SO FUN !!!
I have read this article from a french developer about Linq used to find the list of all the prime numbers < n : http://blogs.developpeur.org/raptorxp/archive/2007/11/26/quizz-linq-la-liste-des-nombres-premiers-en-3-clauses.aspx
Here is another sample: let's try to find the prime number product of an integer:
ex: 504 = 2 * 2 * 2 * 3 * 3 * 7
(from i in Enumerable.Range(2, source) where (source % i == 0) || (source == i) select i).First();
while (source > 1) { var divider = (from i in Enumerable.Range(2, source) where (source % i == 0) || (source == i) select i).First(); source = source / divider; }
public static class IntExtensions { public static IEnumerable<int> ToPrimeNumbersProduct(this int source) { while (source > 1) { var divider = (from i in Enumerable.Range(2, source) where (source % i == 0) || (source == i) select i).First(); yield return divider; source = source / divider; } } }
Now we are done, let's use it:
foreach (var v in 144.ToPrimeNumbersProduct()) Console.WriteLine(v);
Most of the time we prefer to show it by grouping same dividers together powered to their count.
ex: 504 = 2^3 * 3^2 * 7
Once again Linq will allow us to make it very easilly, grouping the enumeration on the values themselves. Then each distinct divider will be the Key of the group and the power will be the count of that group.
foreach (var v in (from i in 504.ToPrimeNumbersProduct() group i by i into g select new { Value = g.Key, Power = g.Count() }) ) Console.WriteLine(v);
We can go a little bit further:
var q = from i in 504.ToPrimeNumbersProduct() group i by i into g select g.Count() > 1 ? g.Key.ToString() + "^" + g.Count().ToString() : g.Key.ToString(); Console.WriteLine(string.Join(" * ", q.ToArray()));