在Java中,如何使用方法来计算一个数字的阶乘值?
这个例子显示了使用9(9)数字的因子计算方法。
package com.yiibai;
public class CalculatingFactorial {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++) {
System.out.printf("%d! = %d\n", counter, factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
执行上面示例代码,得到以下结果 -
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
示例-2
以下是计算阶乘值的另一个例子
package com.yiibai;
public class CalculatingFactorial2 {
public static void main(String[] args) {
int number = 6;
int factorial = number;
for (int i = (number - 1); i > 1; i--) {
factorial = factorial * i;
}
System.out.println("Factorial of 5 is " + factorial);
}
}
执行上面示例代码,得到以下结果 -
Factorial of 5 is 720