Implement factorial recursively and recursively.
If you want to implement a factorial, such as 6*5*4*3*2*1, you may first think of loop traversal. As follows:
class Program
{
static void Main(string[] args)
{
Console. WriteLine ("enter a number ");
int number = Convert.ToInt32(Console.ReadLine());
double result = JieCheng(number);
The factorial result of Console. WriteLine (number. ToString () + "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;
}
}
However, there is another way to implement the factorial: 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 to say, 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 a certain algorithm, this is exactly the time when recursion came into being.
public static double JieCheng(int number) { if (number == 0) { return 1; } return number * JieCheng(number - 1); }
How can we use assembly to implement recursive factorial?
Evaluate the factorial _ recursive call of N (0 ≤ N ≤ 8)
Reference: blog.csdn.net/..3.aspx
Recursion is used to calculate the factorial of a number.
# Include <stdio. h>
Int factorial (int num ){
If (1 = num ){
Return 1;
}
Return (num * factorial (num-1 ));
}
Int main (int argc, char ** argv ){
Int num, result;
Scanf ("% d", & num );
Result = factorial (num );
Printf ("% d \ n", result );
Return 0;
}
This friend didn't make it clear in what language? I wrote one in C to see if it is helpful.
References:
Baike.baidu.com/view/1835559.htm
Baike.baidu.com/view/96473.htm