使用C#拉姆达n个数的阶乘..? [英] factorial of n numbers using c# lambda..?

查看:271
本文介绍了使用C#拉姆达n个数的阶乘..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始用lambda表达式和LINQ表达自我学习玩耍。我带着简单的阶乘的问题这一点。与有些复杂场景,找到给出N个数字(不用其他用递归循环)的阶乘。

I just started playing with lambdas and Linq expression for self learning. I took the simple factorial problem for this. with the little complex scenario where find the factorial for given n numbers (witout using recursive loops).

下面我试图代码。但是,这是行不通的。

Below the code i tried. But this is not working.

public void FindFactorial(int range)
{

    var res = Enumerable.Range(1, range).Select(x => Enumerable.Range(0, x).Where(y => (y > 1)).Select(y => y * (y-1)));            
    foreach (var outt in res)
        Console.WriteLine(outt.ToString());

}

这是我使用的过程


  • 遍历数字1到n - Enumerable.Range(1,范围)

  • 选择每个数x,并再次循环它们高达X倍(而不是
    递归)

  • 和选择号码的其中,(Y =>(Y> 1) )大于1,乘以与
    (Y-1)

  • loop through the numbers 1 to n -- Enumerable.Range(1, range).
  • select each number x and again loop them upto x times (instead of recursion)
  • and select the numbers Where(y => (y > 1)) greater than 1 and multiply that with (y-1)

我知道我搞砸了某个地方。 。谁能告诉我什么是错的,任何其他可能的解决方案。

i know i messed up somewhere. can someone tell me whats wrong and any other possible solution.

编辑:

我要让我的这个线程开启一段时间... ...因为这是我对λ初始步骤..我发现所有的答案非常有用的信息。而它的将是有趣和很好的学习看的方式不同的充。处理这个问题。

i am going to let this thread open for some time... since this is my initial steps towards lambda.. i found all the answers very useful and informative.. And its going to be fun and great learning seeing the differnt ways of approaching this problem.

推荐答案

目前没有递归 - 那就是问题所在。你只是把数字序列,并投影每个号码为*自己本身-1。

Currently there's no recursion - that's the problem. You're just taking a sequence of numbers, and projecting each number to "itself * itself-1".

编写阶乘函数的简单和低效率的方式是:

The simple and inefficient way of writing a factorial function is:

Func<int, int> factorial = null; // Just so we can refer to it
factorial = x => x <= 1 ? 1 : x * factorial(x-1);

for (int i = 1; i <= range; i++)
{
    Console.WriteLine(factorial(i));
}



通常情况下,你再进入的memoization ,以避免重复计算同样的事情。你可能会喜欢上阅读韦斯·戴尔的博客文章这样的事情。

Typically you then get into memoization to avoid having to repeatedly calculate the same thing. You might like to read Wes Dyer's blog post on this sort of thing.

这篇关于使用C#拉姆达n个数的阶乘..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆