This article describes the method of C# using recursive factorization for your reference. Generally speaking, if you want to implement a factorial, such as 6 * 5 * 4 * 3 * 2 * 1, the first thing you think of may be loop traversal.
As shown in the following example:
class Program { static void Main(string[] args) { ("Please enter a number"); int number = Convert.ToInt32(()); double result = JieCheng(number); (() + "The factorial result is:" + ()); (); } 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 there is another way to implement the factorial above: 6 * (6-1) * (6-2) * (6-3) * (6-4) * (6-5) or 6 * (6-1) * (5-1) * (4-1) * (3-1) * (2-1), that is, the following number is always obtained by subtracting 1 from the previous number.
When the implementation logic is the same, and the parameters of the internal recursive method can be obtained by the parameters of the external recursive method through some algorithm, this is the time when the recursive appears.
The implementation code is as follows:
public static double JieCheng(int number) { if (number == 0) { return 1; } return number * JieCheng(number - 1); }
I hope that the examples described in this article will be helpful to friends who learn algorithms.