文章目录
使用递归求一个数的阶乘
Java 代码:
public class Factorial {
public static void main(String[] args) {
System.out.println(fact(6));
}
/**
* Take the factorial of the number.
* @param n
* @return The factorial of the number.
*/
public static int fact(int n) {
if (n < 0) {
throw new IllegalArgumentException(n + " is not allowed!");
}
if (n <= 1) {
return 1;
}
return (n * fact(n - 1));
}
}
运行程序,控制台输出:
720