Recursive factorial, java recursive factorial
| -- Code
Package com. collection; public class Demo2 {public static void main (String [] args) {/*** calculate the factorial of 5 * // solution 1: normal loop int I = 1; for (int x = 1; x <= 5; x ++) {I = I * x;} // System. out. println (I); // solution 2: recursive System. out. println (jc (5);} public static int jc (int I) {if (I = 1) return 1; elsereturn I * jc (I-1 );}}
Process Analysis Diagram
Factorial n! Recursive Algorithm
# Include <stdio. h>
Double fun (int n );
Int main (void)
{
Int n;
Printf ("Enter n :");
Scanf ("% d", & n );
Printf ("% lf \ n", fun (n ));
Return 0;
}
Double fun (int n)
{
If (n = 0 | n = 1)
Return 1;
Else
Return n * fun (n-1 );
}
How can we use recursive functions to calculate factorial?
Int jiecheng (int n)
{
If (n = 1) // if n is equal to 1, return directly.
Return 1;
Else // otherwise, n * jiecheng (n-1) is returned)
Return n * jiecheng (n-1 );
}
For example, n = 3. the running process is as follows:
Call back
Main function 6
Zookeeper
Jiecheng (3) 3 * jiecheng (2) = 3*2 * jiecheng (1) = 3*2*1
Zookeeper
Jiecheng (2) 2 * jiecheng (1) = 2*1
Zookeeper
Jiecheng (1) → 1