factorial of n numbers using c# lambda..?

后端 未结 4 921
名媛妹妹
名媛妹妹 2020-12-17 02:01

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 fact

4条回答
  •  隐瞒了意图╮
    2020-12-17 02:25

    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 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));
    }
    

    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.

提交回复
热议问题