代码改变世界

某个最近不知道为啥很火的小题目的LINQ实现

2009-06-30 16:52  Ivony...  阅读(3271)  评论(21编辑  收藏  举报

题目是老赵的:

http://www.cnblogs.com/JeffreyZhao/archive/2009/06/21/1507847.html

代码如下:

 1    public static IEnumerable<int[]> Compute( int min, int max, int sum, int count )
 2    {
 3      var list = Enumerable.Range( min, max - min + 1 );
 4
 5      if ( count == 1 )
 6        return from item in list where item == sum select new int[] { item };
 7
 8      return list.SelectMany( number => Compute( number, max, sum - number, count - 1 )
 9        .Select( item => item.Concat( new int[] { number } ).ToArray() ) );
10    }

11

 

代码随手写成,仅仅只是用LINQ来实现了一下而已。事实上也能看出LINQ之强大,绝不仅仅是语法糖那么简单

 

另外也顺便出道小题目,大家也可以尝试用LINQ来解一下。

分解质因数,输入一个正整数,要求输出其质因数分解形式

如输入:66,应输出:

66 = 3 * 2 * 11

66 = 6 * 11

是错误的。

 

又如24,应输出:

24 = 2 * 2 * 2 * 3