C implements factorial recursively

  • 2020-08-22 22:38:40
  • OfStack

This article describes the example of C# using recursive factorial method, for your reference. In general, if you want to implement a factorial, say 6 times 5 times 4 times 3 times 2 times 1, the first thing that comes to mind is probably loop traversal.

As shown in the following example:


class Program
{
    static void Main(string[] args)
    {
      Console.WriteLine(" Please enter the 1 The number of ");
      int number = Convert.ToInt32(Console.ReadLine());
      double result = JieCheng(number);
      Console.WriteLine(number.ToString() + " The factorial of is: " + result.ToString());
      Console.ReadKey();
    }
 
    public static double JieCheng(int number)
    {
      if (number == 0)
      {
        return 0;
      }
 
      // The initial value must be set to 1
      double result = 1;
 
      for (int i = number; i >= 1; i--)
      {
        result = result*i;
      }
      return result;
    }
}

But above the factorial of one kind of implementation method: 6 * (6-1) * (6-2) * (6-3) * (6-4) * 6 * (6-5) or (6-1) * (5-1) * (4-1) * (3, 1) * (2-1), that is to say, the number is always behind by the preceding number minus 1.

When the implementation logic is the same, and the parameters of the internal recursive method can be obtained by some algorithm from the parameters of the external recursive method, this is where recursion comes in.

The implementation code is as follows:


public static double JieCheng(int number)
{
  if (number == 0)
  {
 return 1;
  }

  return number * JieCheng(number - 1);
}

I hope the examples in this article will be helpful to you who are learning algorithms.


Related articles: