编写Java函数,计算一个整数的阶乘
发布时间:2023-08-29 21:08:37
可以使用递归或者循环来计算一个整数的阶乘。
使用递归的方法如下:
public class Factorial {
public static int factorial(int n) {
// 0的阶乘为1
if (n == 0) {
return 1;
}
// 使用递归计算阶乘
return n * factorial(n-1);
}
public static void main(String[] args) {
int n = 5;
int result = factorial(n);
System.out.println("Factorial of " + n + " is " + result);
}
}
使用循环的方法如下:
public class Factorial {
public static int factorial(int n) {
int result = 1;
// 使用循环计算阶乘
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
public static void main(String[] args) {
int n = 5;
int result = factorial(n);
System.out.println("Factorial of " + n + " is " + result);
}
}
以上两种方法都可以计算一个整数的阶乘。递归方法将问题分解为更小的子问题,并通过不断调用自身来解决子问题。循环方法通过循环迭代来计算阶乘。两种方法的效果和结果是相同的。
