Java中的階乘程式:n的階乘是所有正整數的乘積。 n
的因數由n!
來表示。 例如:
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
這裏,4!
發音為“4的階乘”。階乘通常用於組合和排列(數學)。
用java語言編寫階乘程式有很多方法。下麵來看看在java中編寫階乘程式的兩種方法。
- 使用迴圈實現的階乘程式
- 使用遞歸實現的階乘程式
1. 使用迴圈實現的階乘程式
下麵來看看在java中使用迴圈的階乘程式。
class FactorialExample {
public static void main(String args[]) {
int i, fact = 1;
int number = 5;// It is the number to calculate factorial
for (i = 1; i <= number; i++) {
fact = fact * i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
執行上面代碼得到以下結果 -
Factorial of 5 is: 120
2. 使用遞歸實現的階乘程式
下麵來看看在java中使用遞歸實現階乘程式。
class FactorialExample2 {
static int factorial(int n) {
if (n == 0)
return 1;
else
return (n * factorial(n - 1));
}
public static void main(String args[]) {
int i, fact = 1;
int number = 4;// It is the number to calculate factorial
fact = factorial(number);
System.out.println("Factorial of " + number + " is: " + fact);
}
}
執行上面代碼得到以下結果 -
Factorial of 4 is: 24
上一篇:
Java基礎實例程式
下一篇:
Java面向對象(OOP)概念