Java中求阶乘的算法
1.一般算法:
public class Factorial {
public static int factorial(int n) {
if (n < 0 || n > 16) {
System.err.println("n must be great than 0 and less than 17");
return -1;
} else if (n == 0) {
return 1;
} else {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
}
public static void main(String args[]) {
System.out.println("result = " + factorial(5));
}
}
运行结果:result = 120
2.递归算法:
public class Factorial {
public static int recursion(int n) {
if (n < 0 || n > 16) {
System.err.println("n must be great than 0 and