May 12, 2021 C#
This article will bring you the method of calculating factories using the C-recursive algorithm, which is explained by a simple example for your reference.
In general, if you want to implement a factor, such as the simple factoring of 6 x 5 x 4 x 3 x 2 x 1, you will generally first think of using circular traversal, as shown in the following code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一个数");
int number = Convert.ToInt32(Console.ReadLine());
double result = JieCheng(number);
Console.WriteLine(number.ToString() + "的阶乘结果是:" + result.ToString());
Console.ReadKey();
}
public static double JieCheng(int number)
{
if (number == 0)
{
return 0;
}
//初始值必须设置为1
double result = 1;
for (int i = number; i >= 1; i--)
{
result = result*i;
}
return result;
}
But there is another way to achieve this factories: 6 x (6-1) x (6-2) x (6-3) x (6-4) x (6-5) or 6 x (6-1) x (5-1) x (4-1) x (3-1) x (2-1), i.e. the number of later numbers is always reduced by the previous number of 1.
When the logic of the implementation 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 when recursive appearance.
The recursive implementation code is as follows:
public static double JieCheng(int number)
{
if (number == 0)
{
return 1;
}
return number * JieCheng(number - 1);
}