程序分析
代码实现
package cn.edu.bennett.test;
/**
* @version:1.0
* @Description:阶乘
* @author bennett
* @date: 2021年9月1日 下午3:58:47
*/
public class Factorial {
public static void main(String[] args) {
// int num = testFactorial1(4);
// int num = testFactorial2(4);
int num = testFactorial3(4);
System.out.println(num);
}
// 递归方法1
private static int testFactorial1(int n) {
if (n <= 1) {
return 1;
} else {
return testFactorial1(n - 1) * n;
}
}
// 递归方法1 优化后
private static int testFactorial3(int n) {
return n <= 1 ? 1:n*testFactorial3(n - 1);
}
//
private static int testFactorial2(int n) {
int num = 1;
for (int j = 1; j <= n; j++) {
num *= j;
}
return num;
}
}