factorial of n numbers using c# lambda..?

后端 未结 4 948
名媛妹妹
名媛妹妹 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:16

    Just to continue on Jon's answer, here's how you can memoize the factorial function so that you don't recompute everything at each step :

    public Func Memoize(Func func)
    {
        Dictionary _resultsCache = new Dictionary();
     return (arg) =>
     {
         TResult result;
         if (!_resultsCache.TryGetValue(arg, out result))
      {
       result = func(arg);
       _resultsCache.Add(arg, result);
      }
      return result;
     };
    }
    
    ...
    
    Func factorial = null; // Just so we can refer to it
    factorial = x => x <= 1 ? 1 : x * factorial(x-1);
    var factorialMemoized = Memoize(factorial);
    var res = Enumerable.Range(1, 10).Select(x => factorialMemoized(x));
    foreach (var outt in res)
        Console.WriteLine(outt.ToString());
    

    EDIT: actually the code above is not correct, because factorial calls factorial, not factorialMemoized. Here's a better version :

    Func factorial = null; // Just so we can refer to it
    Func factorialMemoized = null;
    factorial = x => x <= 1 ? 1 : x * factorialMemoized(x-1);
    factorialMemoized = Memoize(factorial);
    var res = Enumerable.Range(1, 10).Select(x => factorialMemoized(x));
    foreach (var outt in res)
        Console.WriteLine(outt.ToString());
    

    With that code, factorial is called 10 times, against 55 times for the previous version

提交回复
热议问题